gpt4 book ai didi

python - DataFrame.astype() 错误参数

转载 作者:行者123 更新时间:2023-11-28 16:58:19 24 4
gpt4 key购买 nike

astype 在使用 dict of columns 时引发 ValueError

我正在尝试将大 DF 中的稀疏列类型转换(从 float 到 int)。我的问题是 NaN 值。即使 errors 参数设置为 'ignore',在使用列字典时也不会忽略它们。

这是一个玩具示例:

t=pd.DataFrame([[1.01,2],[3.01, 10], [np.NaN,20]])
t.astype({0: int}, errors='ignore')

ValueError: Cannot convert non-finite values (NA or inf) to integer

最佳答案

您可以使用新的 nullable integer Pandas 0.24.0+ 中的 dtype。在使用 astype 之前,您首先需要将任何不完全等于整数的 float 转换为等于整数值(例如舍入、截断等):

In [1]: import numpy as np; import pandas as pd; pd.__version__
Out[1]: '0.24.2'

In [2]: t = pd.DataFrame([[1.01, 2],[3.01, 10], [np.NaN, 20]])

In [3]: t.round().astype('Int64')
Out[3]:
0 1
0 1 2
1 3 10
2 NaN 20

关于python - DataFrame.astype() 错误参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169473/

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