我的索引是日期时间字符串,格式为 '%m/%d/%Y' ('09/26/2007')
当我尝试使用pd.to_datetime
function将索引转换为datetime索引时pd.to_datetime(df.index)
,出现错误消息OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00
熊猫似乎无法检测正确的字符串格式,如何将索引转换为日期时间索引?
谢谢
错误消息的外观,看来您'1/1/0001'
的索引中可能包含字符串。例如,
df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001'])
pd.to_datetime(df.index)
加薪
OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00
由于DatetimeIndex使用datetime64[ns]
不能表示日期0001-01-01的NumPy数组,因此会出现此错误。该datetime64[ns]
D型只能代表范围中的日期[1678 AD, 2262 AD]
。
有一个熊猫github问题讨论了这个限制。
目前,推荐的解决方案是使用PeriodIndex而不是DatetimeIndex:
df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001'])
df.index = pd.PeriodIndex(df.index, freq='D')
产量
0
2007-09-26 1
1-01-01 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句