Python 将两个dataframe与重复列组合
我有两个数据帧,A和B。Python 将两个dataframe与重复列组合,python,pandas,data-manipulation,Python,Pandas,Data Manipulation,我有两个数据帧,A和B。 我想通过pandas.concat([A,B],axis=1)将它们组合起来。 但是,其中有一些重复的列,如下所示: # A ID Col1 Col2 Col3 Col4 Col5 TL # B Col1 Col2 Col3 Col4 Col5 数据B中Col1-Col5下的值与数据A中的值不同 如何使用列获取新的数据帧,ID Col1 Col2 Col3 Col4 Col5 TL ID和TL来自数据A,Col1-Col5来自数据B da = pd.DataFram
我想通过pandas.concat([A,B],axis=1)将它们组合起来。
但是,其中有一些重复的列,如下所示:
# A
ID Col1 Col2 Col3 Col4 Col5 TL
# B
Col1 Col2 Col3 Col4 Col5
数据B
中Col1-Col5
下的值与数据A
中的值不同如何使用列获取新的数据帧,
ID Col1 Col2 Col3 Col4 Col5 TL
ID
和TL
来自数据A
,Col1-Col5
来自数据B
da = pd.DataFrame({'ID':list('abcde'), 'c1':range(5),'c2':range(5), 'TL':list('qrstu')})
db = pd.DataFrame({'c1':range(10,15),'c2':range(20,25)})
不清楚你需要什么,这里有一些
da.update(db)
da[['c1','c2']] = db[['c1','c2']]
cols = [c for c in da.columns if c in db.columns]
da[cols] = db[cols]
dc = pd.concat([da['ID'],db[['c1','c2']], da['TL']], 1)
使用@wwii设置。
让我们先使用组合\u
:
db.combine_first(da)
输出:
ID TL c1 c2
0 a q 10 20
1 b r 11 21
2 c s 12 22
3 d t 13 23
4 e u 14 24
这些数据帧是否有确保它们之间对齐的索引?顺序已经确定。只需组合。提供示例数据帧使ppl更容易回答
da['c1','c2']=db[['c1','c2']]
?pd.concat([da['ID'],db['c1','c2']],da['TL']],1)
?@PeterChan此解决方案对您有帮助吗?你会考虑一个解决办法吗?@ ScottBoston谢谢!它是有效的,应该是一个很好的解决方案!