获取DataFrame的Datetime列的工作日/星期几 [英] Get weekday/day-of-week for Datetime column of DataFrame
问题描述
我有一个类似于以下内容的DataFrame df
(摘录,"Timestamp"是索引):
I have a DataFrame df
like the following (excerpt, 'Timestamp' are the index):
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']
,其中包含相应的时间戳记的星期几/星期几.
I need a new column df['weekday']
with the respective weekday/day-of-week of the timestamps.
我怎么能得到这个?
推荐答案
Use the new dt.dayofweek
property:
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 the situation where the Timestamp
is your index you need to reset the index and then call the dt.dayofweek
property:
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
属性而不分配
Strangely if you try to create a series from the index in order to not reset the index you get NaN
values as does using the result of reset_index
to call the dt.dayofweek
property without assigning the result of reset_index
back to the original 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
属性,因此以下内容将有效并且更加紧凑:
As pointed out to me by user @joris you can just access the weekday
attribute of the index so the following will work and is more compact:
df['Weekday'] = df.index.weekday
这篇关于获取DataFrame的Datetime列的工作日/星期几的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!