2017-08-06 68 views
1

我在這裏找不到答案。 我有兩個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 

我想的結果是一個數據幀:

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 

有沒有一種方法來合併它們的索引dataframes,同時增加新的列?

回答

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 
+1

謝謝@jezrael。我感謝你的幫助:) –

+0

@jezrale如果我想在日期列中添加星期值,那麼列日就會像這樣結束:day [1,thu,4,mon]。這也有可能嗎? –

+0

我覺得最簡單的是重命名專欄,給我一秒鐘。 – jezrael