我正在尝试将日期转换为周期间,然后获得期间的第一部分。
df['Date'] = df['Date (mm/dd/yyyy)'].dt.to_period('W').apply(lambda r: r.start_time)但它给了我一个错误
AttributeError: 'NaTType' object has no attribute 'start_time'我使用的是pandas 0.25.2版本。
虽然它以前是运行的,但这次没有运行。无法确定发生了什么。请帮助解决此错误
发布于 2019-10-22 20:33:15
使用技巧np.nan != np.nan,这样您就可以添加if-else语句或将Series.to_timestamp与默认how='s'一起使用
rng = pd.date_range('2017-04-03', periods=10)
df = pd.DataFrame({'Date (mm/dd/yyyy)': rng})
df.loc[0, 'Date (mm/dd/yyyy)'] = np.nan
df['Date'] = (df['Date (mm/dd/yyyy)'].dt.to_period('W')
.apply(lambda r: r.start_time if r == r else np.nan))
df['Date1'] = df['Date (mm/dd/yyyy)'].dt.to_period('W').dt.to_timestamp()
print (df)
Date (mm/dd/yyyy) Date Date1
0 NaT NaT NaT
1 2017-04-04 2017-04-03 2017-04-03
2 2017-04-05 2017-04-03 2017-04-03
3 2017-04-06 2017-04-03 2017-04-03
4 2017-04-07 2017-04-03 2017-04-03
5 2017-04-08 2017-04-03 2017-04-03
6 2017-04-09 2017-04-03 2017-04-03
7 2017-04-10 2017-04-10 2017-04-10
8 2017-04-11 2017-04-10 2017-04-10
9 2017-04-12 2017-04-10 2017-04-10https://stackoverflow.com/questions/58504341
复制相似问题