在2个数据框架之间切换行
我有2个看起来像这样的数据范围:
df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'col2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'col3': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'cond': [5000, 6000, 6001, 5000, 6002, 6003, 5000, 6004, 6005, 5001]})
df2 = pd.DataFrame({'col1': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'col2': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'col3': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'cond': [6000, 5000, 5001, 6000, 5002, 5003, 6000, 5004, 5005, 6001]})
我需要根据条件列在两个数据范围之间交换行,5000±100的值应在一个数据范围内,而值6000±100在另一个数据范围内:
df_expected1 = pd.DataFrame({'col1': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'col2': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'col2': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'cond': [5000, 5000, 5001, 5000, 5002, 5003, 5000, 5004, 5005, 5001]})
df_expected2 = pd.DataFrame({'col1': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'col2': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'col2': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'cond': [6000, 6000, 6001, 6000, 6002, 6003, 6000, 6004, 6005, 6001]})
I have 2 dataframes looking like this :
df1 = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'col2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'col3': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'cond': [5000, 6000, 6001, 5000, 6002, 6003, 5000, 6004, 6005, 5001]})
df2 = pd.DataFrame({'col1': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'col2': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'col3': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
'cond': [6000, 5000, 5001, 6000, 5002, 5003, 6000, 5004, 5005, 6001]})
I need to swap rows between the two dataframes based on the condition column, the values which are 5000±100 should be in one dataframe and the values 6000±100 in another:
df_expected1 = pd.DataFrame({'col1': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'col2': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'col2': [1, 9, 8, 4, 6, 5, 7, 3, 2, 10],
'cond': [5000, 5000, 5001, 5000, 5002, 5003, 5000, 5004, 5005, 5001]})
df_expected2 = pd.DataFrame({'col1': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'col2': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'col2': [10, 2, 3, 7, 5, 6, 4, 8, 9, 1],
'cond': [6000, 6000, 6001, 6000, 6002, 6003, 6000, 6004, 6005, 6001]})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先将两个数据范围串联,然后基于列
cond
:我在这里假设
df1
和df2
是数据范围。值5500
是任意选择的,也许您需要更改此内容。如果输出需要是字典,则可以使用
.to_dict()
。First concatenate the two dataframes and then split them based on column
cond
:I assumed here that
df1
anddf2
are dataframes. Value5500
is arbitrarily chosen, maybe you need to change this.If the output needs to be a dictionary, you can use
.to_dict()
.