我有两个这样的表:
Table A:
id id2 value
1 1 a
1 2 b
2 1 c
3 1 d
Table B:
id value2
1 e
2 g
3 h
我需要加入他们,所以我会得到这样的东西:
Table needed:
id id2 value value2
1 1 a e
1 2 b e
2 1 c g
3 1 d h
Excel、Python 或 R 都可以。事实上,我需要如果表 A 中的 id 与表 B 中的 id 匹配,则表 b 中的值将添加到匹配行中。然而,两个表的大小并不相同,有时表 b 中的 id 在表 a 中不存在。我只需要表a中的那些。
最佳答案
最快的是使用 map
:
df1['value2'] = df1['id'].map(df2.set_index('id')['value2'])
print (df1)
id id2 value value2
0 1 1 a e
1 1 2 b e
2 2 1 c g
3 3 1 d h
编辑:
print (df2)
id value2
0 1 e
1 1 p
2 2 g
3 3 h
df1['value2'] = df1['id'].map(df2.set_index('id')['value2'])
print (df1)
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
解决方案是删除它们:
print (df2)
id value2
0 1 e
1 1 p
2 2 g
3 3 h
df2 = df2.drop_duplicates(subset='id')
print (df2)
id value2
0 1 e
2 2 g
3 3 h
df1['value2'] = df1['id'].map(df2.set_index('id')['value2'])
print (df1)
id id2 value value2
0 1 1 a e
1 1 2 b e
2 2 1 c g
3 3 1 d h
具有 merge
重复值的解决方案并左连接:
df = pd.merge(df1, df2, on='id', how='left')
print (df)
id id2 value value2
0 1 1 a e
1 1 1 a p
2 1 2 b e
3 1 2 b p
4 2 1 c g
5 3 1 d h
关于python - Python按列合并不同大小的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537717/