将包含 NaN 的 Pandas 列转换为 dtype `int` [英] Convert Pandas column containing NaNs to dtype `int`
本文介绍了将包含 NaN 的 Pandas 列转换为 dtype `int`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将数据从 .csv 文件读取到 Pandas 数据框,如下所示.对于其中一列,即id
,我想将列类型指定为int
.问题是 id
系列缺少/空值.
I read data from a .csv file to a Pandas dataframe as below. For one of the columns, namely id
, I want to specify the column type as int
. The problem is the id
series has missing/empty values.
当我在读取 .csv 时尝试将 id
列转换为整数时,我得到:
When I try to cast the id
column to integer while reading the .csv, I get:
df= pd.read_csv("data.csv", dtype={'id': int})
error: Integer column has NA values
或者,我在阅读以下内容后尝试转换列类型,但这次我得到:
Alternatively, I tried to convert the column type after reading as below, but this time I get:
df= pd.read_csv("data.csv")
df[['id']] = df[['id']].astype(int)
error: Cannot convert NA to integer
我该如何解决这个问题?
How can I tackle this?
推荐答案
整数列中缺少 NaN 代表是一个 熊猫gotcha".
The lack of NaN rep in integer columns is a pandas "gotcha".
通常的解决方法是简单地使用浮动.
The usual workaround is to simply use floats.
这篇关于将包含 NaN 的 Pandas 列转换为 dtype `int`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文