我将数据从.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

我该如何解决这个问题?


当前回答

首先,您需要指定新的整数类型Int8(…Int64),它可以处理空整数数据(pandas版本>= 0.24.0)

df = df.astype('Int8')

但是你可能想要只针对包含NaN/null的整数数据的特定列:

df = df . astype((’col1’:’Int8’’col2’:’Int8’、’col3’:’Int8’)

此时,NaN将被转换为<NA>,如果您希望使用df.fillna()更改默认空值,则需要在希望更改的列上强制使用对象数据类型,否则您将看到 TypeError: <U1不能转换为IntegerDtype

你可以通过 Df = Df .astype(对象)如果你不介意将每个列的数据类型更改为对象(单独地,每个值的类型仍然保留)…或 Df = Df。如果您喜欢针对单个列,则Astype ({"col1":对象,"col2":对象})。

这应该有助于强制将混合了null值的整数列保持为整数格式,并将空值更改为您喜欢的任何值。我不能说这种方法的效率,但它适用于我的格式化和打印目的。

其他回答

import pandas as pd

df= pd.read_csv("data.csv")
df['id'] = pd.to_numeric(df['id'])

我的用例是在加载到DB表之前修改数据:

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

删除nan,转换为int,转换为str,然后重新插入nan。

它不漂亮,但它完成了工作!

我在使用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

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

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

因为我在这里没有看到答案,我不妨加上它:

如果你因为某种原因仍然不能处理np,可以用一行程序将nan转换为空字符串。Na或者pd。我和我一样,在使用旧版本的熊猫库时:

df select_dtypes(“当家”)。astype (str) fillna(- 1)。replace(“- 1”、“)