如何将pandas的DatetimeIndex转换为Timestamp数组?
解决DatetimeIndex转Timestamp数组及儒略日计算问题
问题原因
DatetimeIndex的底层存储元素是numpy.datetime64类型,而pd.Timestamp.to_julian_date方法仅支持pandas.Timestamp对象,直接传入DatetimeIndex会触发'numpy.datetime64' object has no attribute 'year'错误。
最简解决方法(推荐)
DatetimeIndex本身内置了to_julian_date方法,无需额外用np.vectorize包装,直接调用即可完成儒略日计算:
# 直接通过索引计算儒略日 julianDay = Weather.index.to_julian_date()
转换为Timestamp数组的方法
如果确实需要将DatetimeIndex转换为Timestamp数组,可通过以下方式实现:
# 将DatetimeIndex转换为Timestamp数组 timestamp_array = Weather.index.to_series().apply(pd.Timestamp).values # 再使用你原来的vectorize方法计算儒略日 get_julianDate = np.vectorize(pd.Timestamp.to_julian_date) julianDay = get_julianDate(timestamp_array)
内容的提问来源于stack exchange,提问作者Benjamin Brannon
相关产品推荐
相关产品推荐

