首页 > 解决方案 > 管理零日期 - 无法将浮点 NaN 转换为整数

问题描述

大家早,

我需要在我的文件中管理大于 2261 的日期。执行时出现上述错误:

m = df['maturity_date'].str[:4].astype(int) > 2261
ValueError: cannot convert float NaN to integer

导致错误的列的详细信息:

display(df['maturity_date'].dtypes)
dtype('O')

display(df['maturity_date'].describe())
count                        3709
unique                        781
top       2166-09-23 00:00:00.000
freq                          234
Name: maturity_date, dtype: object

display(df[df['maturity_date'].isnull()])
No records returned

display(df[df['maturity_date']==0]['maturity_date'] )
764     0
931     0
1173    0
Name: maturity_date, dtype: object

由于无法转换零,可能引发错误?我打算在它工作后更新日期的代码:

#Convert dates greater than 2261
display(df['maturity_date'].str[:4].astype(int) > 2261)
df['maturity_date'] = df['maturity_date'].mask(m, '2261' +  to df['maturity_date'].str[4:]) # for all dates greater than python max date replace
df['maturity_date'] = pd.to_datetime(df['maturity_date']) 

标签: pythonpandasdatedataframeint

解决方案


这应该有效。您需要首先将整数转换为字符串,以便使用该.str方法。

m = df['maturity_date'].astype('str').str[:4].astype(int) > 2261

问题是,如果您不想在整数值上调用 .str 。当您这样做时,它会将其转换为NaN,然后您会遇到转换为整数的问题。

例如:

import pandas as pd
df = pd.DataFrame({'value': [0, '0', '0000', '000']})

df.value.str[:4]
#0     NaN
#1       0
#2    0000
#3     000
#Name: value, dtype: object

df.value.astype('str').str[:4]
#0       0
#1       0
#2    0000
#3     000
#Name: value, dtype: object

推荐阅读