python type_error ai_generated true

ValueError: 您正尝试在 int64 和 object 列上合并。如要继续请使用 pd.concat

ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concat

ID: python/pandas-merge-dtype-mismatch

其他格式: JSON · Markdown 中文 · English
80%修复率
89%置信度
0证据数
2024-04-25首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

pd.merge 要求连接键的 dtype 匹配。未显式指定 dtype 读取的 CSV 常使一个 DataFrame 的 ID 为 object(字符串),另一个为 int。

English

pd.merge requires matching dtypes on join keys. A CSV read without explicit dtype inference often leaves IDs as object (string) in one frame and int in the other.

generic

解决方案

  1. 95% 成功率
    df2['id'] = df2['id'].astype(df1['id'].dtype); pd.merge(df1, df2, on='id')
  2. 90% 成功率
    Read both with pd.read_csv(..., dtype={'id': 'int64'})

无效尝试

常见但无效的做法:

  1. 95% 失败

    Same ValueError

  2. 50% 失败

    Changes dtype but breaks numeric comparisons downstream