将两个数据范围之间的行交换与模式
我有2个看起来像这样的数据范围:
在每个数据框中,值列中的模式为1-2。 (只是为了证明模式,这些值对我的问题并不重要)
df1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [20, 1000, 10001, 21, 1000, 1002, 22, 1003, 1007,23]}
df2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [1000, 21, 22, 1000, 22, 23, 1000, 20, 21, 1000]}
我需要在两个数据范围之间交换行,以便结果是:
df_expected1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [20, 21, 22, 21, 22, 23, 22, 20, 21,23]}
df_expected2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [1000, 1000, 10001, 1000, 1000, 1002, 1000, 1003, 1007, 1000]}
I have 2 dataframes looking like this :
In each dataframe there is pattern of 1-2 in the values column. (the values are not significant to my problem, just to demonstrate the pattern)
df1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [20, 1000, 10001, 21, 1000, 1002, 22, 1003, 1007,23]}
df2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [1000, 21, 22, 1000, 22, 23, 1000, 20, 21, 1000]}
I need to swap rows between the two dataframes so that the outcome would be :
df_expected1 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [20, 21, 22, 21, 22, 23, 22, 20, 21,23]}
df_expected2 = {'idx': [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'values': [1000, 1000, 10001, 1000, 1000, 1002, 1000, 1003, 1007, 1000]}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
知道掉期需要的索引来自
3N-2
,您可以制作掩码,然后使用numpy.Where
:输出:输出:
Knowing that swap-needed indices are from
3n-2
, you can make mask then usenumpy.where
:Output:
知道两个dataframes之间的索引相同:
输出:输出:
This should do it, knowing that the indices are the same between two dataframes :
Output :
在下面的代码段中,我假设
df1
和df2
中的索引相等,并且来自df1
的值总是应该大于DF2
。输出:
In the code snippet below, I assumed that indexes in both
df1
anddf2
were equal and that values fromdf1
are always supposed to be greater thandf2
.Output: