【发布时间】:2015-03-21 17:50:40
【问题描述】:
我肯定在这里遗漏了一些简单的东西。尝试合并 pandas 中的两个数据框,它们的列名大多相同,但右侧数据框有一些左侧没有的列,反之亦然。
>df_may
id quantity attr_1 attr_2
0 1 20 0 1
1 2 23 1 1
2 3 19 1 1
3 4 19 0 0
>df_jun
id quantity attr_1 attr_3
0 5 8 1 0
1 6 13 0 1
2 7 20 1 1
3 8 25 1 1
我尝试过使用外部连接加入:
mayjundf = pd.DataFrame.merge(df_may, df_jun, how="outer")
但这会产生:
Left data columns not unique: Index([....
我还指定了要加入的单个列(例如on = "id"),但这会复制除id 之外的所有列,例如attr_1_x、attr_1_y,这并不理想。我还将列的整个列表(有很多)传递给on:
mayjundf = pd.DataFrame.merge(df_may, df_jun, how="outer", on=list(df_may.columns.values))
产量:
ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
我错过了什么?我想获得一个附加了所有行的df,并在可能的情况下填充attr_1、attr_2、attr_3,在它们不出现的地方填充NaN。这似乎是一个非常典型的数据处理工作流程,但我被卡住了。
提前致谢。
【问题讨论】:
标签: python pandas dataframe data-munging