我将数据从.csv文件读取到Pandas数据框架,如下所示。对于其中一列,即id,我想将列类型指定为int。问题是id系列有缺失/空值。

当我试图在读取.csv时将id列强制转换为整数时,我得到:

df= pd.read_csv("data.csv", dtype={'id': int}) 
error: Integer column has NA values

或者,我尝试转换列类型后,阅读如下,但这一次我得到:

df= pd.read_csv("data.csv") 
df[['id']] = df[['id']].astype(int)
error: Cannot convert NA to integer

我该如何解决这个问题?


当前回答

这里的大多数解决方案都告诉您如何使用占位符整数来表示null。但是,如果不确定源数据中不会出现整数,那么这种方法就没有帮助。我的方法将格式浮动没有他们的十进制值,并将null转换为None。结果是一个对象数据类型,当加载到CSV中时,它看起来像一个带空值的整数字段。

keep_df[col] = keep_df[col].apply(lambda x: None if pandas.isnull(x) else '{0:.0f}'.format(pandas.to_numeric(x)))

其他回答

类似于@hibernado的答案,但保持为整数(而不是字符串)

df[col] = df[col].fillna(-1)
df[col] = df[col].astype(int)
df[col] = np.where(df[col] == -1, np.nan, df[col])

我在使用pyspark时遇到了这个问题。由于这是运行在jvm上的代码的python前端,它需要类型安全,使用float而不是int是不可取的。我把熊猫包裹起来,解决了这个问题。函数中的Read_csv,该函数将在将用户定义的列转换为所需类型之前,用用户定义的填充值填充用户定义的列。这是我最终使用的:

def custom_read_csv(file_path, custom_dtype = None, fill_values = None, **kwargs):
    if custom_dtype is None:
        return pd.read_csv(file_path, **kwargs)
    else:
        assert 'dtype' not in kwargs.keys()
        df = pd.read_csv(file_path, dtype = {}, **kwargs)
        for col, typ in custom_dtype.items():
            if fill_values is None or col not in fill_values.keys():
                fill_val = -1
            else:
                fill_val = fill_values[col]
            df[col] = df[col].fillna(fill_val).astype(typ)
    return df

试试这个:

df[id]]

如果你输出它的dtypes,你将得到id Int64而不是普通的Int64

整数列中缺少NaN代表是熊猫的“陷阱”。

通常的解决方法是简单地使用浮动。

在0.24版本中。+ pandas获得了保存缺少值的整型dtypes的能力。

可空整数数据类型。

Pandas可以使用arrays.IntegerArray表示可能缺少值的整数数据。这是在pandas中实现的扩展类型。它不是整数的默认dtype,也不会被推断出来;你必须显式地将dtype传递给array()或Series:

arr = pd.array([1, 2, np.nan], dtype=pd.Int64Dtype())
pd.Series(arr)

0      1
1      2
2    NaN
dtype: Int64

将列转换为可空整数使用:

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