我正在对一个存在多个输入错误的大型旧数据集进行排序。我想通过迭代一行来根据条件查找和更改类型错误来清理文档。现在,当我尝试删除 pandas 中的小时分钟秒时,出现以下错误。
Out of bounds nanosecond timestamp: 3016-03-09 00:00:00
我的想法是这样的:
import pandas as pd
df = pd.read_excel(r'raw data.xlsx', header = 0)
for date in Dates:
if date is out of bounds date time:
replace str[0-3] with Year, inplace = True
df['Date'].dt.year,month,day
print(df)
典型的数据集输入错误可能是第 4 项中的日期
Item Description Date Year ...
1 Ketchup400 2015-10-27 00:00:00 2015 ...
2 Ketchup600 2018-02-16 00:00:00 2018 ...
3 Mustard800 2015-10-02 00:00:00 2015 ...
4 Mustard200 3016-03-09 00:00:00 2016 ...
1 Ketchup400 2018-02-26 00:00:00 2018 ...
... ... ... ... ...
我想从日期中删除小时、分钟和秒,更正日期并打印新文件...输出应该类似于:
Item Description Date Year ...
1 Ketchup400 2015-10-27 2015 ...
2 Ketchup600 2018-02-16 2018 ...
3 Mustard800 2015-10-02 2015 ...
4 Mustard200 2016-03-09 2016 ...
1 Ketchup400 2018-02-26 2018 ...
... ... ... ... ...
最佳答案
最简单的解决方案是通过第一个 -
将列 Year
添加到吐出的 Date
列并转换为日期时间:
s = df['Year'].astype(str) + '-' + df['Date'].astype(str).str.split('-', n=1).str[1]
df['Date'] = pd.to_datetime(s, errors='coerce')
print (df)
Item Description Date Year ...
0 1 Ketchup400 2015-10-27 2015 ...
1 2 Ketchup600 2018-02-16 2018 ...
2 3 Mustard800 2015-10-02 2015 ...
3 4 Mustard200 2016-03-09 2016 ...
4 1 Ketchup400 2018-02-26 2018 ...
另一个性能更好的解决方案是通过 to_datetime
获取所有未解析的日期时间和 errors='coerce'
参数,通过检查缺失值并添加到原始值来仅解析过滤后的行 Series.combine_first
行处理类似于第一个解决方案:
date = pd.to_datetime(df['Date'], errors='coerce')
df1 = df[date.isna()]
print (df1)
Item Description Date Year ...
3 4 Mustard200 3016-03-09 00:00:00 2016 ...
s = (pd.to_datetime(df1['Year'].astype(str) + '-' +
df1['Date'].astype(str).str.split('-', n=1).str[1]))
print (s)
3 2016-03-09
dtype: datetime64[ns]
df['Date'] = date.combine_first(s)
print (df)
Item Description Date Year ...
0 1 Ketchup400 2015-10-27 2015 ...
1 2 Ketchup600 2018-02-16 2018 ...
2 3 Mustard800 2015-10-02 2015 ...
3 4 Mustard200 2016-03-09 2016 ...
4 1 Ketchup400 2018-02-26 2018 ...
关于pandas - 如何从数据集中搜索输入错误(日期)并根据条件替换它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108921/