为什么 inner join 在 pandas 中工作如此奇怪?
例如:
import pandas as pd
import io
t1 = ('key,col1\n'
'1,a\n'
'2,b\n'
'3,c\n'
'4,d')
t2 = ('key,col2\n'
'1,e\n'
'2,f\n'
'3,g\n'
'4,h')
df1 = pd.read_csv(io.StringIO(t1), header=0)
df2 = pd.read_csv(io.StringIO(t2), header=0)
print(df1)
print()
print(df2)
print()
print(df2.join(df1, on='key', how='inner', lsuffix='_l'))
输出:
key col1
0 1 a
1 2 b
2 3 c
3 4 d
key col2
0 1 e
1 2 f
2 3 g
3 4 h
key_l col2 key col1
0 1 e 2 b
1 2 f 3 c
2 3 g 4 d
如果我不指定 lsuffix
,它说
ValueError: columns overlap but no suffix specified: Index(['key'], dtype='object')
这个函数与 SQL 的 JOIN 有什么不同吗?为什么要创建一个带有后缀的额外“键”列?为什么只有 3 行? 我希望它输出这样的东西:
key col1 col2
0 1 a e
1 2 b f
2 3 c g
3 4 d h
最佳答案
要事第一:
你想要的是合并
df1.merge(df2)
join
默认在 index
上合并.您可以指定 on
参数仅表示左侧的哪一列与右侧的索引匹配。
这些可能有助于说明
df1.set_index('key').join(df2.set_index('key'))
df1.join(df2.set_index('key'), on='key')
您的示例匹配 df2
的索引看起来像 [0, 1, 2, 3]
与 key
df1
栏目看起来像 [1, 2, 3, 4]
这就是为什么你得到 NaN
在col2
什么时候key_l
是4
df1.join(df2, on='key', lsuffix='_l', how='outer')
关于python - 解释 pandas DataFrame join 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39755981/