[英]Getting Out of bounds nanosecond timestamp error while using fillna in python?
嘗試將默認值傳遞給 null 值列時出現out of bounds nanosecond timestamp
錯誤
df3['check_date']=df3['eventDate0142'].fillna(df3['statusDateTi'].fillna(pd.to_datetime('9999-12-31')))
這怎么能解決。?
問題出在 pandas 最大時間戳是:
print (pd.Timestamp.max)
2262-04-11 23:47:16.854775807
所以在 pandas 中出現錯誤:
print (pd.to_datetime('9999-12-31'))
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 9999-12-31 00:00:00
樣本:
df1 = pd.DataFrame({'eventDate0142': [np.nan, np.nan, '2016-04-01'],
'statusDateTi': [np.nan, '2019-01-01', '2017-04-01']})
df3 = df1.apply(pd.to_datetime)
print (df3)
eventDate0142 statusDateTi
0 NaT NaT
1 NaT 2019-01-01
2 2016-04-01 2017-04-01
可能的解決方案是使用純 python,但隨后所有 pandas datetimelike 方法都失敗了 - 所有數據都轉換為date
s:
from datetime import date
print (date.fromisoformat('9999-12-31'))
9999-12-31
df3['check_date'] = (df3['eventDate0142'].dt.date
.fillna(df3['statusDateTi'].dt.date
.fillna(date.fromisoformat('9999-12-31'))))
print (df3)
eventDate0142 statusDateTi check_date
0 NaT NaT 9999-12-31
1 NaT 2019-01-01 2019-01-01
2 2016-04-01 2017-04-01 2016-04-01
print (df3.dtypes)
eventDate0142 datetime64[ns]
statusDateTi datetime64[ns]
check_date object
dtype: object
或者通過Series.dt.to_period
將時間戳轉換為每日周期,然后使用Periods
表示越界span :
print (pd.Period('9999-12-31'))
9999-12-31
df3['check_date'] = (df3['eventDate0142'].dt.to_period('d')
.fillna(df3['statusDateTi'].dt.to_period('d')
.fillna(pd.Period('9999-12-31'))))
print (df3)
eventDate0142 statusDateTi check_date
0 NaT NaT 9999-12-31
1 NaT 2019-01-01 2019-01-01
2 2016-04-01 2017-04-01 2016-04-01
print (df3.dtypes)
eventDate0142 datetime64[ns]
statusDateTi datetime64[ns]
check_date period[D]
dtype: object
如果分配回所有列:
df3['eventDate0142'] = df3['eventDate0142'].dt.to_period('d')
df3['statusDateTi'] = df3['statusDateTi'].dt.to_period('d')
df3['check_date'] = (df3['eventDate0142']
.fillna(df3['statusDateTi']
.fillna(pd.Period('9999-12-31'))))
print (df3)
eventDate0142 statusDateTi check_date
0 NaT NaT 9999-12-31
1 NaT 2019-01-01 2019-01-01
2 2016-04-01 2017-04-01 2016-04-01
print (df3.dtypes)
eventDate0142 period[D]
statusDateTi period[D]
check_date period[D]
dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.