gpt4 book ai didi

pandas - 无法将 nan 转换为 int(但没有 nan)

转载 作者:行者123 更新时间:2023-12-04 16:20:14 24 4
gpt4 key购买 nike

我有一个包含一列浮点数的数据框,我想将其转换为 int:

> df['VEHICLE_ID'].head()
0 8659366.0
1 8659368.0
2 8652175.0
3 8652174.0
4 8651488.0

从理论上讲,我应该能够使用:
> df['VEHICLE_ID'] = df['VEHICLE_ID'].astype(int)

但我得到:
Output: ValueError: Cannot convert NA to integer

但我很确定这个系列中没有 NaN:
> df['VEHICLE_ID'].fillna(999,inplace=True)
> df[df['VEHICLE_ID'] == 999]
> Output: Empty DataFrame
Columns: [VEHICLE_ID]
Index: []

这是怎么回事?

最佳答案

基本上错误是告诉你你 NaN值(value)观,我将说明为什么您的尝试没有揭示这一点:

In [7]:
# setup some data
df = pd.DataFrame({'a':[1.0, np.NaN, 3.0, 4.0]})
df
Out[7]:
a
0 1.0
1 NaN
2 3.0
3 4.0

现在尝试转换:
df['a'].astype(int)

这提出:
ValueError: Cannot convert NA to integer

但后来你尝试了这样的事情:
In [5]:
for index, row in df['a'].iteritems():
if row == np.NaN:
print('index:', index, 'isnull')

这没有打印任何内容,但是 NaN不能像这样使用相等来评估,实际上它有一个特殊的属性,它将返回 False与自己比较时:
In [6]:
for index, row in df['a'].iteritems():
if row != row:
print('index:', index, 'isnull')

index: 1 isnull

现在它打印行,你应该使用 isnull可读性:
In [9]:
for index, row in df['a'].iteritems():
if pd.isnull(row):
print('index:', index, 'isnull')

index: 1 isnull

那么该怎么办?我们可以删除行: df.dropna(subset='a') ,或者我们可以使用 fillna 替换:
In [8]:
df['a'].fillna(0).astype(int)

Out[8]:
0 1
1 0
2 3
3 4
Name: a, dtype: int32

关于pandas - 无法将 nan 转换为 int(但没有 nan),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985063/

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