Pandas 从日期类型列中获取星期几

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46515267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:33:23  来源:igfitidea点击:

Pandas Get Day of Week from date type column

pythonpandasdataframe

提问by kdragger

I'm using Python 3.6 and Pandas 0.20.3.

我使用的是 Python 3.6 和 Pandas 0.20.3。

I have a column that I've converted to date type from datetime. All I need is the date. I have it as a derived column for ease of use. But I'm looking to do some further operations via a day of the week calculation. I can get the day of week from a datetime type but not from the date. It seems to me that this should be possible but I've tried multiple variations and not found success.

我有一个从日期时间转换为日期类型的列。我只需要日期。为了便于使用,我将其作为派生列。但我希望通过一周中的一天计算做一些进一步的操作。我可以从日期时间类型中获取星期几,但不能从日期中获取。在我看来,这应该是可能的,但我尝试了多种变体,但都没有成功。

Here is an example:

下面是一个例子:

import numpy as np
import pandas as pd
df = pd.DataFrame({'date':['2017-5-16','2017-5-17']})
df['trade_date']=pd.to_datetime(df['date'])

I can get the day of the week from the datetime column 'trade_date'.

我可以从日期时间列“trade_date”中获取星期几。

df['dow']=df['trade_date'].dt.dayofweek
df
    date    trade_date  dow
0   2017-5-16   2017-05-16  1
1   2017-5-17   2017-05-17  2

But if I have a date, rather than a datetime, no dice: For instance:

但是如果我有一个日期,而不是一个日期时间,没有骰子:例如:

df['trade_date_2']=pd.to_datetime(df['date']).dt.date

And then:

进而:

df['dow_2']=df['trade_date_2'].dt.dayofweek

I get (at the end):

我得到(最后):

AttributeError: Can only use .dt accessor with datetimelike values

I've tried various combinations of dayofweek(), weekday, weekday() which, I realize, highlight my ignorance of exactly how Pandas works. So ... any suggestions besides adding another column which is the datetime version of column trade_date? I'll also welcome explanations of why this is not working.

我尝试了 dayofweek()、weekday、weekday() 的各种组合,我意识到,这凸显了我对 Pandas 工作原理的无知。所以......除了添加另一列是列trade_date的日期时间版本之外还有什么建议吗?我也欢迎解释为什么这不起作用。

回答by jezrael

There is problem it is difference between pandas datetime(timestamps) where are implemented .dtmethods and python datewhere not.

问题在于pandas datetime(时间戳)在何处实现.dt方法和python date在何处不实现方法之间存在差异。

#return python date
df['trade_date_2']= pd.to_datetime(df['date']).dt.date

print (df['trade_date_2'].apply(type))
0    <class 'datetime.date'>
1    <class 'datetime.date'>
Name: trade_date_2, dtype: object

#cannot work with python date
df['dow_2']=df['trade_date_2'].dt.dayofweek

Need convert to pandas datetime:

需要转换为pandas datetime

df['dow_2']= pd.to_datetime(df['trade_date_2']).dt.dayofweek

print (df)
        date trade_date_2  dow_2
0  2017-5-16   2017-05-16      1
1  2017-5-17   2017-05-17      2

So the best is use:

所以最好是使用:

df['date'] = pd.to_datetime(df['date'])
print (df['date'].apply(type))
0    <class 'pandas._libs.tslib.Timestamp'>
1    <class 'pandas._libs.tslib.Timestamp'>
Name: date, dtype: object

df['trade_date_2']= df['date'].dt.date
df['dow_2']=df['date'].dt.dayofweek
print (df)
        date trade_date_2  dow_2
0 2017-05-16   2017-05-16      1
1 2017-05-17   2017-05-17      2

EDIT:

编辑:

Thank you Bharath shettyfor solution working with python date- failed with NaT:

感谢Bharath shetty提供的解决方案python date- 失败NaT

df = pd.DataFrame({'date':['2017-5-16',np.nan]})

df['trade_date_2']= pd.to_datetime(df['date']).dt.date
df['dow_2'] = df['trade_date_2'].apply(lambda x: x.weekday()) 

AttributeError: 'float' object has no attribute 'weekday'

AttributeError: 'float' 对象没有属性 'weekday'

Comparing solutions:

比较解决方案:

df = pd.DataFrame({'date':['2017-5-16','2017-5-17']})
df = pd.concat([df]*10000).reset_index(drop=True)

def a(df):
    df['trade_date_2']= pd.to_datetime(df['date']).dt.date
    df['dow_2'] = df['trade_date_2'].apply(lambda x: x.weekday()) 
    return df

def b(df):
    df['date1'] = pd.to_datetime(df['date'])
    df['trade_date_21']= df['date1'].dt.date
    df['dow_21']=df['date1'].dt.dayofweek
    return (df)

def c(df):
    #dont write to column, but to helper series 
    dates = pd.to_datetime(df['date'])
    df['trade_date_22']= dates.dt.date
    df['dow_22']=        dates.dt.dayofweek
    return (df)

In [186]: %timeit (a(df))
10 loops, best of 3: 101 ms per loop

In [187]: %timeit (b(df))
10 loops, best of 3: 90.8 ms per loop

In [188]: %timeit (c(df))
10 loops, best of 3: 91.9 ms per loop