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

我该如何解决这个问题?


当前回答

首先删除包含NaN的行。然后对其余行进行整型转换。 最后再次插入删除的行。 希望能奏效

其他回答

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

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

使用pd.to_numeric ()

df["DateColumn"] = pd.to_numeric(df["DateColumn"])

简单干净

试试这个:

df[id]]

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

与Int64的问题,像许多其他的解决方案,是如果你有空值,他们被替换为<NA>值,这与熊猫默认的'NaN'函数,如isnull()或fillna()不工作。或者,如果您将值转换为-1,则可能会删除您的信息。我的解决方案有点蹩脚,但将用np提供int值。Nan,允许Nan函数在不影响您的值的情况下工作。

            def to_int(x):
                try:
                    return int(x)
                except:
                    return np.nan

            df[column] = df[column].apply(to_int)
df.loc[~df['id'].isna(), 'id'] = df.loc[~df['id'].isna(), 'id'].astype('int')