<分区>
我使用以下代码通过指定每个列的类型来读取 csv:
clean_pdf_type=pd.read_csv('table_updated.csv',usecols=col_names,dtype =col_types)
但它有错误:
ValueError: Integer column has NA values in column 298
不确定如何跳过 NA?
<分区>
我使用以下代码通过指定每个列的类型来读取 csv:
clean_pdf_type=pd.read_csv('table_updated.csv',usecols=col_names,dtype =col_types)
但它有错误:
ValueError: Integer column has NA values in column 298
不确定如何跳过 NA?
最佳答案
参见 NumPy or Pandas: Keeping array type as integer while having a NaN value
在 int
dtype 系列中不能有 NaN
值。这是不可避免的,因为 NaN
值被认为是 float
:
import numpy as np
type(np.nan) # float
最好的办法是将这些列读作 float
。如果您随后能够将 NaN
值替换为填充值,例如 0
或 -1
,您可以相应地处理并转换为 整数
:
int_cols = ['col1', 'col2', 'col3']
df[int_cols] = df[int_cols].fillna(-1)
df[int_cols] = df[int_cols].apply(pd.to_numeric, downcast='integer')
混合 int
和 float
值的替代方案将导致一系列 dtype object
。不推荐。
关于python - read_csv 使用 dtypes 但列中有 na 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52002271/