【问题标题】:How to left merge two dataframes with nan without changing types from integer to float types如何在不将类型从整数类型更改为浮点类型的情况下将两个数据帧与 nan 合并
【发布时间】:2022-01-27 03:43:29
【问题描述】:

我正在尝试通过特定列上的键合并两个 pandas 数据帧(df1 和 df2),但我想保留两个 dfs 上没有匹配键的行。最后,我想要一个 df3 缺少该键列的值。当我使用以下代码执行此操作时,我的整数将转换为浮点类型:

df3 = pd.merge(df1, df2, how= 'left', on=['Species Name'])

我可以使用以下方法将它们转换为 int64:

df3['物种 ID'] = df3['物种 ID'].astype('Int64')

但随后我的 NaN 被转换为“pandas._libs.missing.NAType”的“”。这是一个问题,因为我想使用 psycopg2 将 df3 插入到 postgresql 数据库中,并且它不接受这样的 Nas。有谁知道如何正确合并这些 dfs 或如何在不弄乱 Na 格式的情况下修复浮点数?

df1:

Sample ID Species Name
A X
B Y
C NaN

df2:

Species Name Species ID
X 1
Y 2

我最终得到了什么:

Sample ID Species Name Species ID
A X 1.000
B Y 2.000
C NaN NaN

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    使用pd.IntXDtype 作为Species ID 列的数据类型:

    df2['Species ID'] = df2['Species ID'].astype(pd.Int8Dtype())
    df3 = pd.merge(df1, df2, how= 'left', on=['Species Name'])
    print(df3)
    
    # Output
      Sample ID Species Name  Species ID
    0         A            X           1
    1         B            Y           2
    2         C          NaN        <NA>
    

    更多信息:Nullable integer data type

    【讨论】:

    • 感谢您的建议。我收到以下错误。 TypeError:不能安全地将非等效 int64 转换为 int8。无论哪种方式。如果我最终在''中得到 NaN,就像你提到的那样,我在导出到 postgres 时不会遇到同样的问题吗?
    • 我能够使用:df2['Species ID'] = df2['Species ID'].astype(pd.Int64Dtype()) 但是将其导出到数据库时,我得到了: 无法插入数据!无法调整类型 'NAType' 我需要缺少的信息为 NaN 而不是
    • 尝试将pd.NA修改为无:.replace({'Species ID': {pd.NA: None}})
    • 感谢 Corralien,这行得通!我还找到了第二个可以正常工作的替代方案:df3.astype(object).where(pd.notnull(df3), None)
    猜你喜欢
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多