将包含NaN的Pandas列转换为dtype`int` [英] Convert Pandas column containing NaNs to dtype `int`

查看:294
本文介绍了将包含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

我该如何解决?

推荐答案

.

通常的解决方法是仅使用浮点数.

The usual workaround is to simply use floats.

这篇关于将包含NaN的Pandas列转换为dtype`int`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆