【问题标题】:Converting pandas series and datetime objects转换熊猫系列和日期时间对象
【发布时间】:2019-03-24 21:27:59
【问题描述】:

我有一系列日期格式:

df['myDateTimes']
0                       NaT
1       2017-07-23 00:26:50
2                       NaT
3       2017-07-31 04:07:24

(其中第一个数字只是 pandas 数据帧索引) 我想将这些转换为修改后的朱利安日期

from datetime import datetime, timedelta
import julian
import datetime
dtime  = julian.to_jd(df['myDateTimes'], fmt='jd')

只是给出一个

AttributeError: 'Series' object has no attribute 'month'

df['myDateTimes'] 是熊猫系列,(我认为) julian.to_jd 需要一个 datetime.datetime 对象。

【问题讨论】:

    标签: python pandas datetime dataframe time-series


    【解决方案1】:

    使用 apply ,因为你有 NaT julian 不会预料到的,所以我们在将 datetime 传递给 julian 之前进行过滤

    s[s.notna()].apply(lambda x : julian.to_jd(x,fmt='jd')).reindex(s.index)
    Out[139]: 
    0             NaN
    1    2.457958e+06
    2             NaN
    3    2.457966e+06
    dtype: float64
    

    【讨论】:

    • 我得到一个:“NameError: name 's' is not defined”错误。我将 s 替换为 df['myDateTimes'] 并收到“AttributeError: 'str' object has no attribute 'month'”错误。
    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多