Python 如何通过根据数据帧重命名来连接两个数据帧?
嘿,我想连接两个数据帧df1和df2。 但我希望它们根据dataframe重命名,因为我需要比较每一列 我有一个数据帧df1,如下所示:Python 如何通过根据数据帧重命名来连接两个数据帧?,python,pandas,dataframe,concatenation,Python,Pandas,Dataframe,Concatenation,嘿,我想连接两个数据帧df1和df2。 但我希望它们根据dataframe重命名,因为我需要比较每一列 我有一个数据帧df1,如下所示: 1 2 3 0 a p q 1 b n r 2 c o s 1 2 3 0 a t read 1 b l unread 2 c w read I和另一个数据帧df2,如下所
1 2 3
0 a p q
1 b n r
2 c o s
1 2 3
0 a t read
1 b l unread
2 c w read
I和另一个数据帧df2,如下所示:
1 2 3
0 a p q
1 b n r
2 c o s
1 2 3
0 a t read
1 b l unread
2 c w read
我还想根据各自的datafarame对列进行重命名:
df1_1 df2_1 df1_2 df2_2 df1_3 df2_3
0 a a p t q read
1 b b n l r unread
2 c c o w s read
此外,我想列被重新安排相应的s,我可以比较。
请提供解决方案。
谢谢你使用pandas.join()
和参数lsuffix=''u-df1',rsuffix=''u-df2'
示例
df1 = pd.DataFrame({1:[1,2], 2:[3,4]})
df2 = pd.DataFrame({1:[1,2], 2:[3,4]})
df1 = df1.join(df2, lsuffix='_df1', rsuffix='_df2')
df
>>>
1_df1 2_df1 1_df2 2_df2
0 1 3 1 3
1 2 4 2 4
也许这已经足够近了。如果没有,您可以在以后使用以下行重命名列:
df1.rename({name: name.split('_')[1] +'_'+ name.split('_')[0] for name in df1.columns},
axis=1)
>>>
df1_1 df1_2 df2_1 df2_2
0 1 3 1 3
1 2 4 2 4
使用
添加前缀
,然后使用重塑
重新排列列:
x1 = df1.add_prefix('df1_')
x2 = df2.add_prefix('df2_')
cols = np.vstack((x1.columns, x2.columns)).T.reshape(-1)
x1.join(x2).reindex(cols, axis=1)
输出:
df1_1 df2_1 df1_2 df2_2 df1_3 df2_3
0 a a p t q read
1 b b n l r unread
2 c c o w s read
嗯,在你把前缀添加到你的答案中之前,我的答案中没有添加前缀选项吗?是的。这是真的。如果你愿意的话,我可以删除它。是的,谢谢,一般来说,你最好只添加有别于其他答案的解决方案谢谢你的建议。