python - 管理零日期 - 无法将浮点 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'])
解决方案
这应该有效。您需要首先将整数转换为字符串,以便使用该.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
推荐阅读
- python - 如何将多维列表中的两个索引配对并与其他索引匹配
- javascript - 异步代码在语句中不起作用
- javascript - 打字稿声明定义的字符串或任何字符串的类型
- javascript - 如何使用 jQuery 和 javascript 显示随机图像?
- python - sklearn 如何知道哪些列是 One-Hot 编码的?
- python - 使用 django rest auth 验证用户电子邮件没有错误
- javascript - 无法在一页中获取多个选项卡的总记录值
- machine-learning - 朴素贝叶斯 - 没有类标签 0 的样本
- c# - 将 .NET 分离签名验证转换为 bouncycastle
- python - 在 Python 中分阶段迭代列表