aha*_*jib 11 python join dataframe pandas
我是pandas的新手,我正在尝试根据一个特定列的相等性加入两个数据帧.例如,假设我有以下内容:
df1
A B C
1 2 3
2 2 2
df2
A B C
5 6 7
2 8 9
Run Code Online (Sandbox Code Playgroud)
两个数据帧都具有相同的列,并且只有一列(例如A)的值可能相等.我想要的输出是这样的:
df3
A B C B C
2 8 9 2 2
Run Code Online (Sandbox Code Playgroud)
列'A'的值在两个数据帧中都是唯一的.
谢谢
vk1*_*011 13
pd.concat([df1.set_index('A'),df2.set_index('A')], axis=1, join='inner')
Run Code Online (Sandbox Code Playgroud)
如果您希望将列维护A为非索引,则:
pd.concat([df1.set_index('A'),df2.set_index('A')], axis=1, join='inner').reset_index()
Run Code Online (Sandbox Code Playgroud)
Pau*_*l H 11
或者,您可以这样做:
df3 = df1.merge(df2, on='A', how='inner', suffixes=('_1', '_2'))
Run Code Online (Sandbox Code Playgroud)
然后,您可以跟踪每个值的来源