python - 熊猫没有在不同的列上合并 - 键错误或 NaN
问题描述
我试图用我当前的数据来模仿我的问题。我正在尝试使用 pandas 合并不同列名(代码和编号)上的两个数据框,并从 df2 (位置)中只带来一列。我收到密钥错误或 NaN。
- 两者都是作为数据框导入的 CSV 文件;
- 两个列名都没有空格;
- 两列具有相同的 d.type
我曾尝试在这里查看其他答案,将编码答案复制并粘贴到我的部分中,但仍然会出现错误或 NaN。
df1:
[['Name', 'Income', 'Favourite superhero', 'Code', 'Colour'],
['Joe', '80000', 'Batman', '10004', 'Red'],
['Christine', '50000', 'Superman', '10005', 'Brown'],
['Joey', '90000', 'Aquaman', '10002', 'Blue']
df2:
[['Number', 'Language', 'Location'],
['10005', 'English', 'Sudbury'],
['10002', 'French', 'Ottawa'],
['10004', 'German', 'New York']]
what I tried:
data = pd.merge(CSV1,
CSV2[['Location']],
left_on='Code',
right_on='Number',
how='left')
data = pd.merge(CSV1,
CSV2[['Location']],
left_on='Code',
right_index=True,
how='left')
I am trying to have df1 with the location column from df2 for each instance where Number
and Code are the same.
解决方案
对于您的两个命令都有效,您需要Number
存在于右侧数据框中。对于第一个命令,您需要Number
在merge
. 对于第二个命令,您需要set_index
在正确的切片数据帧上,不需要 drop Number
。我相应地修改了您的命令:
CSV1.merge(CSV2[['Number', 'Location']], left_on='Code', right_on='Number', how='left').drop('Number', 1)
或者
CSV1.merge(CSV2[['Number', 'Location']].set_index('Number'), left_on='Code', right_index=True, how='left')
Out[892]:
Name Income Favourite superhero Code Colour Location
0 Joe 80000 Batman 10004 Red New York
1 Christine 50000 Superman 10005 Brown Sudbury
2 Joey 90000 Aquaman 10002 Blue Ottawa
推荐阅读
- android - 如何在同一个 kotlin-multiplatform 项目中设置 android、ios 和 kotlin-frontend?
- arduino - 如何使用 Arduino Mega 和 USB Host shield 从/向连接的设备读取/写入十六进制数据?
- swift - 键入时如何刷新 UISearchBar 搜索结果而无需按“搜索”按钮?有什么本土方法吗?
- xaml - 背景图像在 Emulator 和 Real Device Andriod 9.0 上显示,但在 8.1 及更低版本上不显示
- r - `devtools::test()`、`RNGversion` 和 `sample` 产生不同的结果
- c - 尝试将 Haskell 函数导出到 C 时,元组“无法在外部调用中编组”
- scala - 在 Akka Typed 中处理死去的演员
- python - 如何将 python2.7 和 3.7 都安装在 alpine docker 映像中
- javascript - 如何在 React Native 中等待来自 firebase 身份验证的持久用户
- php - 为什么 WordPress 仍然说我的 PHP 最大输入变量尚未更新?