简体   繁体   English

在同一索引上合并数据帧

[英]merging dataframes on the same index

I can't find the answer to this in here. 我在这里找不到答案。 I have two dataframes: 我有两个数据框:

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

And I'd like the result to be one dataframe: 我希望结果是一个数据帧:

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

Is there a way to merge the dataframes on their indexes, while adding new columns? 有没有办法在添加新列的同时合并索引上的数据框?

You can use DataFrame.combine_first : 您可以使用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

For custom order of columns create columns names by numpy.concatenate , pd.unique and then add reindex_axis : 对于列的自定义顺序,请通过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

EDIT: 编辑:

Use rename columns: 使用重命名列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM