为 DataFrame 的日期时间列获取 weekday/day-of-week

Get weekday/day-of-week for Datetime column of DataFrame

我有一个 DataFrame df 如下(摘录,'Timestamp' 是索引):

Timestamp              Value
2012-06-01 00:00:00     100
2012-06-01 00:15:00     150
2012-06-01 00:30:00     120
2012-06-01 01:00:00     220
2012-06-01 01:15:00      80
...and so on.

我需要一个新列 df['weekday'],其中包含相应的 weekday/day-of-week 时间戳。

我怎样才能得到这个?

使用新的 dt.dayofweek 属性:

In [2]:

df['weekday'] = df['Timestamp'].dt.dayofweek
df
Out[2]:
            Timestamp  Value  weekday
0 2012-06-01 00:00:00    100        4
1 2012-06-01 00:15:00    150        4
2 2012-06-01 00:30:00    120        4
3 2012-06-01 01:00:00    220        4
4 2012-06-01 01:15:00     80        4

Timestamp 是您的索引的情况下,您需要重置索引,然后调用 dt.dayofweek 属性:

In [14]:

df = df.reset_index()
df['weekday'] = df['Timestamp'].dt.dayofweek
df
Out[14]:
            Timestamp  Value  weekday
0 2012-06-01 00:00:00    100        4
1 2012-06-01 00:15:00    150        4
2 2012-06-01 00:30:00    120        4
3 2012-06-01 01:00:00    220        4
4 2012-06-01 01:15:00     80        4

奇怪的是,如果您尝试从索引创建系列以便不重置索引,您将获得 NaN 值,就像使用 reset_index 调用 dt.dayofweek 的结果一样属性 没有将 reset_index 的结果赋值回原来的 df:

In [16]:

df['weekday'] = pd.Series(df.index).dt.dayofweek
df
Out[16]:
                     Value  weekday
Timestamp                          
2012-06-01 00:00:00    100      NaN
2012-06-01 00:15:00    150      NaN
2012-06-01 00:30:00    120      NaN
2012-06-01 01:00:00    220      NaN
2012-06-01 01:15:00     80      NaN
In [17]:

df['weekday'] = df.reset_index()['Timestamp'].dt.dayofweek
df
Out[17]:
                     Value  weekday
Timestamp                          
2012-06-01 00:00:00    100      NaN
2012-06-01 00:15:00    150      NaN
2012-06-01 00:30:00    120      NaN
2012-06-01 01:00:00    220      NaN
2012-06-01 01:15:00     80      NaN

编辑

正如用户@joris 向我指出的那样,您可以访问索引的 weekday 属性,因此以下内容将起作用并且更紧凑:

df['Weekday'] = df.index.weekday

如果 Timestamp 列是 datetime 值,那么您可以只使用:
df['weekday'] = df['Timestamp'].apply(lambda x: x.weekday())

df['weekday'] = pd.to_datetime(df['Timestamp']).apply(lambda x: x.weekday())

如果其他人对多索引数据框有同样的问题,这里是基于@joris 解决方案为我解决的问题:

df['Weekday'] = df.index.get_level_values(1).weekday

对我来说日期是 get_level_values(1) 而不是 get_level_values(0),后者适用于外部索引。

您可以通过以下方式获得:

import datetime
df['weekday'] = pd.Series(df.index).dt.day_name()