合并同一索引上的数据帧

时间:2017-08-06 14:56:30

标签: python pandas

我在这里找不到答案。 我有两个数据帧:

index,  name,   color, day
   0    Nan     Nan    Nan
   1    b       red    thu
   2    Nan     Nan    Nan
   3    d       green  mon

index,  name,  color,   week
    0    c      blue    1
    1    Nan    Nan     Nan
    2    t      yellow  4
    3    Nan    Nan     Nan

我希望结果是一个数据帧:

index,  name,   color,  day,   week  
    0       c   Blue    Nan    1
    1       b   red     thu    Nan
    2       t   yellow  Nan    4
    3       d   green   mon    Nan

有没有办法在添加新列的同时合并索引上的数据框?

1 个答案:

答案 0 :(得分:2)

您可以使用DataFrame.combine_first

df = df1.combine_first(df2)
print (df)
    color  day name  week
0    blue  NaN    c   1.0
1     red  thu    b   NaN
2  yellow  NaN    t   4.0
3   green  mon    d   NaN

对于列的自定义顺序,按numpy.concatenatepd.unique创建列名称,然后添加reindex_axis

cols = pd.unique(np.concatenate([df1.columns, df2.columns]))
df = df1.combine_first(df2).reindex_axis(cols, axis=1)
print (df)
  name   color  day  week
0    c    blue  NaN   1.0
1    b     red  thu   NaN
2    t  yellow  NaN   4.0
3    d   green  mon   NaN

编辑:

使用重命名列:

df = df1.combine_first(df2.rename(columns={'week':'day'}))
print (df)
  name   color  day
0    c    blue    1
1    b     red  thu
2    t  yellow    4
3    d   green  mon