首页 > 解决方案 > 从 Pandas 中的 UTC_TIME 系列获取星期几

问题描述

当我做

df.dtypes

, 出现这个

utc_time         int64

utc_time 的一个例子是:1536444323321

我在这里找到了将 utc_time (epoch) 更改为星期几的代码

df['Week_Day'] = 
datetime.fromtimestamp(df['utc_time']/1000).strftime("%A")

但我收到此错误:

TypeError                                 Traceback (most recent call 
last)
<ipython-input-124-b3277c232078> in <module>()
      2 # df['intage'] = df['utc_time'].astype(int)
      3 # df['intage'] = df['utc_time'].dt.days
----> 4 df['Week_Day'] = 
datetime.fromtimestamp(df['utc_time']/1000).strftime("%A")

/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in 
wrapper(self)
    115             return converter(self.iloc[0])
    116         raise TypeError("cannot convert the series to "
--> 117                         "{0}".format(str(converter)))
    118 
    119     return wrapper

TypeError: cannot convert the series to <class 'int'>

标签: pythonpandasutcdayofweek

解决方案


首先,将您的列/系列转换为日期时间对象。 df['column'] = pd.to_datetime(df['column'])

然后,您有两个选择:

  • 选项 1 - 使用.dt访问器: df['column'].dt.weekday将工作日作为整数提供

  • 选项 2 - 使用 pandasTimestamp对象: df['column'].apply(pd.Timestamp.weekday)

但我真的推荐选项 1。


推荐阅读