python - 解释 pandas DataFrame join 的工作原理

标签 python python-3.x pandas dataframe

为什么 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)

enter image description here


join默认在 index 上合并.您可以指定 on参数仅表示左侧的哪一列与右侧的索引匹配。

这些可能有助于说明

df1.set_index('key').join(df2.set_index('key'))

enter image description here

df1.join(df2.set_index('key'), on='key')

enter image description here


您的示例匹配 df2 的索引看起来像 [0, 1, 2, 3]key df1 栏目看起来像 [1, 2, 3, 4]
这就是为什么你得到 NaNcol2什么时候key_l4

df1.join(df2, on='key', lsuffix='_l', how='outer')

enter image description here

关于python - 解释 pandas DataFrame join 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39755981/

相关文章:

python - 设置单个值时如何避免SettingWithCopyWarning?

python - Keras 形状 'ValueError'

python - 对列表中的 Python 字典对象进行排序

android - 如何将 Kivy 应用部署到 Google 应用商店?

python - 单击鼠标按钮时如何连续移动字符

Python:如何填充引用另一个数据框列的平均值

Python - 从列表中提取并 reshape

python - Django 在尝试通过 django-admin-tools 创建菜单时引发配置不当

python - 映射字典时在单独的 pandas 列中设置值

python - Pandas:将项目转换为字典,其中 orderID 是字典键