将包含python-NaN的Pandas列转换为dtype`int '
将. csv文件中的数据导入到Pandas数据帧中。 如下所示。 对于任一列,即id,希望在int中指定列类型。 问题是id系列有缺失值/null值。
如果在导入. csv时尝试将id列转换为整数,则可以执行以下操作:
df=PD.read_CSV(data.CSV ),dtype={'id': int} ) ) ) ) ) ) )。
error :集成电路nhasnavalues
或者,您试图在阅读后转换列类型。 情况如下,但这次得到了以下内容。
df=PD.read_CSV(data.CSV ) )
df['id']=df['id']].astype(int ) )。
error : cannotconvertnatointeger
怎么解决这个问题?
rhubarb asked 2019-07-25t 20336055336059 z
11个解决方案
113电压
整数列缺少NaN rep的是熊猫的“陷阱”。
通常的解决方法是简单地使用浮动。
andyhaydenanswered 2019-07-25t 20336056336016 z
19电压
我的用例是在加载到数据库表之前更新数据。
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 ) )。
删除NaNs,将其转换为int,转换为str,然后重新插入NAN。
虽然不漂亮,但是我完成了工作!
hibernadoanswered 2019-07-25t 20336056336054 z
12电压
在0.24版。 pandas获得了保存具有缺少值的整数dtypes的能力。
可以指定空的整数数据类型。
Pandas可以使用Series表示可能缺少值的整数数据。 这是在pandas中实现的扩展类型。 它不是整数的默认dtype,不是估计的; 必须明确地将dtype传递给Series或Series :
arr=PD.array ([ 1,2,np.nan],dtype=pd.Int64Dtype ) )
PD.series(arr ) ) ) ) ) ) ) )。
0 1
1 2
2 NaN
dtype: Int64
jezraelanswered 2019-07-25t 20336057336032 z
3电压
如果可以修改存储的数据并使用sentinel值丢失id。 根据列名推测的常见用例可以通过在id为整数且严格大于零时使用0作为标记值来编写
if row['id']:
regular_process(row )
else:
special _ process (行)
gboffianswered 2019-07-25t 20336057336058 z
2电压
如果可以删除具有NaN值的行,则可以使用. fillna ()。
df=df.dropna(subset=['id'] )。
或者,使用. fillna (和. astype ) )将NaN替换为值并将其转换为int。
处理具有大整数的CSV文件时遇到此问题,一些文件丢失(NaN )。 将浮点用作类型不是可选的,因为它可能会丢失精度。
我的解决办法是将str作为中间类型使用。 然后,可以稍后将代码中的字符串转换为int。 将NaN替换为0,但可以选择任意值。
df=PD.read_CSV(filename,dtype={'id':str} )
df['id']=df['id'].fillna('0' ).astype(int ) () ) ) ) ) 65 )
为了说明,有浮点数可能会失去精度的例子:
s='12345678901234567890 '
f=浮动(s )
I=int(f )
I2=int(s )
打印(f,I,i2 ) ) )。
输出如下。
1.2345678901234567 e 19123456789012345678901234567168123456789012345678901234567890
elomageanswered 2019-07-25t 20336058336052 z
2电压
现在可以将包含NaNs的pandas列创建为dtype int。 这是因为它已正式添加到pandas 0.24.0中
熊猫0.24.x发行说明引用:“Panda
s已经获得了保存缺少值的整数dtypes的能力mork answered 2019-07-25T20:59:25Z
0 votes
假设您的DateColumn格式为3312018.0应作为字符串转换为03/31/2018。 并且,一些记录丢失或0。
df['DateColumn'] = df['DateColumn'].astype(int)
df['DateColumn'] = df['DateColumn'].astype(str)
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.zfill(8))
df.loc[df['DateColumn'] == '00000000','DateColumn'] = '01011980'
df['DateColumn'] = pd.to_datetime(df['DateColumn'], format="%m%d%Y")
df['DateColumn'] = df['DateColumn'].apply(lambda x: x.strftime('%m/%d/%Y'))
Justin Malinchak answered 2019-07-25T20:59:51Z
0 votes
我在使用pyspark时遇到了这个问题。 因为这是在jvm上运行的代码的python前端,所以它需要类型安全,并且使用float而不是int不是一个选项。 我通过将pandas pd.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
Neuneck answered 2019-07-25T21:00:17Z
0 votes
首先删除包含NaN的行。 然后对剩余的行进行Integer转换。最后,再次插入已删除的行。希望它会奏效
kamran kausar answered 2019-07-25T21:00:43Z
0 votes
如果您绝对想要在列中组合整数和NaN,则可以使用“对象”数据类型:
df['col'] = (
df['col'].fillna(0)
.astype(int)
.astype(object)
.where(df['col'].notnull())
)
这将用一个整数替换NaN(无关紧要),转换为int,转换为object并最终重新插入NaN。
jmenglund answered 2019-07-25T21:01:16Z
0 votes
这里的大多数解决方案都告诉您如何使用占位符整数来表示空值。 如果您不确定整数不会出现在源数据中,那么这种方法没有用。 我的方法将格式化浮点数而没有它们的十进制值,并将空值转换为无。 结果是一个对象数据类型,当加载到CSV中时,它看起来像一个带有空值的整数字段。
keep_df[col] = keep_df[col].apply(lambda x: None if pandas.isnull(x) else '{0:.0f}'.format(pandas.to_numeric(x)))
Corbin answered 2019-07-25T21:01:42Z