pd.DataFrame假設我有以下兩個
first = pd.DataFrame(data={'col': ['bla', 'blub'], 'a': [1, 2], 'b': [3, 4]})
second = pd.DataFrame(data={'col': ['bla', 'blub'], 'a': [5, 6], 'b': [7, 8]})
這創造了這兩個
# first
col a b
--------------
0 bla 1 3
1 blub 2 4
# second
col a b
--------------
0 bla 5 7
1 blub 6 8
現在我只想加入這兩個col可以輕松完成的事情
pd.merge(left=first, right=second, on=['col'], suffixes=['_first', '_second'])
# Current result
col a_first b_first a_second b_second
-----------------------------------------------
0 bla 1 3 5 7
1 blub 2 4 6 8
但是我真的不想擁有這些列后綴,我想擁有列名,但有一個列索引來說明它來自哪個表。像這樣的東西
# Wanted result
first second
col a b a b
-------------------------
0 bla 1 3 5 7
1 blub 2 4 6 8
有人可以幫忙嗎?
uj5u.com熱心網友回復:
讓我們concat一起做,axis=1并使用keys引數來添加額外的列級別
pd.concat([first.set_index('col'), second.set_index('col')], keys=('first', 'second'), axis=1)
結果
first second
a b a b
col
bla 1 3 5 7
blub 2 4 6 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524428.html
