我有以下数据框:
print(df1)
day month quantity Operation_type
21 6 6 2
24 6 4 2
...
print(df2)
day month quantity Operation_type
22 6 10 1
23 6 15 1
...
我想获取以下数据集:
print(final_df)
day month quantity Operation_type
21 6 6 2
22 6 10 1
23 6 15 1
24 6 4 2
...
我尝试使用:
final_df = pd.merge(df1, df2, on=['day','month'])
但它创建了一个巨大的数据集并且似乎无法正常工作;
此外,如果日期和月份相同,我想将 Operation_type == 2
的行粘贴到 ==1
的行之前。
我该如何解决这个问题?
最佳答案
要将 DataFrame 合并为一个,您不需要合并,您需要 pd.concat
。要正确排序,只需使用 DataFrame.sort_values
pd.concat([df1, df2]).sort_values(by=['day', 'month', 'Operation_type'],
ascending=[True, True, False])
关于python - 在日和月合并 2 个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364256/