gpt4 book ai didi

python - 将 float 转换为 int 并保留空值

转载 作者:太空狗 更新时间:2023-10-30 01:27:19 35 4
gpt4 key购买 nike

我有以下数据框,我想将“b”列中的值转换为整数

    a   b       c
0 1 NaN 3
1 5 7200.0 20
2 5 580.0 20

以下代码抛出异常“ValueError:无法将 NA 转换为整数”

df['b'] = df['b'].astype(int)

我如何仅将 float 转换为 int 并保留空值?

最佳答案

当您的系列包含 float 和 nan 并且您想要转换为整数时,当您尝试将 float 转换为 numpy 整数时会出现错误,因为存在 na 值。

不要做:

df['b'] = df['b'].astype(int)

从 pandas >= 0.24 开始,现在有一个内置的 pandas 整数。这确实允许整数 nan。注意 'Int64' 中的大写字母。这是 pandas 整数,而不是 numpy 整数。

那么,这样做:

df['b'] = df['b'].astype('Int64')

有关 pandas 整数 na 值的更多信息:
https://pandas.pydata.org/pandas-docs/stable/user_guide/gotchas.html#nan-integer-na-values-and-na-type-promotions

关于python - 将 float 转换为 int 并保留空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39690742/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com