python - Pandas 合并(左连接)的关键错误

标签 python pandas merge

我下面有两个数据框,df_purchase(1) 和 df_login(2)

+--------+-----+--------+------------+--------------------+-------------+--------------------------+
|        | age | gender |    ttp     |       count        | sum(amount) |          region          |
+--------+-----+--------+------------+--------------------+-------------+--------------------------+
|  49427 | 63  | M      | 824.731412 | 2                  | 25.00       | Omaha, Nebraska          |
|  28433 | 49  | M      | 1.166250   | 2                  | 41.94       | Catasauqua, Pennsylvania |
|   4162 | 29  | M      | 5.620949   | 2                  | 51.78       | Eagle Center, Iowa       |
|  18747 | 43  | M      | 153.502072 | 2                  | 23.84       | Pacific, Washington      |
|  45173 | 59  | M      | 0.027257   | 2                  | 13.98       | De Soto, Missouri        |
+--------+-----+--------+------------+--------------------+-------------+--------------------------+

+--------+-----+--------+------------+--------------------+-------------+--------------------------+
|        | age | gender | count      | region             |             |                          |
| 671766 | 84  | M      | 13900      | New York, New York |             |                          |
| 671166 | 84  | F      | 7619       | New York, New York |             |                          |
| 672209 | 85  | F      | 6483       | New York, New York |             |                          |
| 672671 | 85  | M      | 5808       | New York, New York |             |                          |
| 195201 | 34  | M      | 3817       | New York, New York |             |                          |
+--------+-----+--------+------------+--------------------+-------------+--------------------------+

我正在尝试使用以下 pandas 代码将 df_logins 加入 df_purchase 的年龄、性别和地区:

df = pd.merge(df_purchase, df_login[['count']],
                       how='left', on=['age', 'gender', 'region'])

但是,我不断收到此错误:KeyError: 'age' 有什么想法吗?

最佳答案

KeyError由此产生:

df = pd.merge(df_purchase, df_login[['count']] <- this selects just count column,
                       how='left', on=['age', 'gender', 'region'])

您已经专门从 df_login 中选择了一个列,您需要这个:

df = pd.merge(df_purchase, df_login,
                       how='left', on=['age', 'gender', 'region'])

我假设这不是您的完整数据,因为您在 df_login 的年龄和地区列中没有共同的值。

关于python - Pandas 合并(左连接)的关键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29242387/

相关文章:

python - VIM/Python插入模式完成弹出菜单

python - 具有多个列索引和标题行的 Excel 通过 pandas 转换为 Python 字典

python - 将 pandas 列传递给函数时出现 "ValueError: The truth value of a Series is ambiguous"

python - 抓取 pandas 系列中除一个元素外的所有元素

SVN - 无法将分支合并回主干 - 许多树冲突

python - 通过删除行来消除 DataFrame 中一列的倾斜?

python - 如何检查字符串是否为十进制/ float ?

Python 跟踪和分析

python - 在 Pandas 循环中合并多个系列

r - 更改数据帧结构(两个数据帧到一个)