Extract day and month from a datetime object

后端 未结 4 1553
臣服心动
臣服心动 2021-01-06 01:26

I have a column with dates in string format \'2017-01-01\'. Is there a way to extract day and month from it using pandas?

I have converted the column to

4条回答
  •  渐次进展
    2021-01-06 02:07

    Use dt to get the datetime attributes of the column.

    In [60]: df = pd.DataFrame({'date': [datetime.datetime(2018,1,1),datetime.datetime(2018,1,2),datetime.datetime(2018,1,3),]})
    
    In [61]: df
    Out[61]:
            date
    0 2018-01-01
    1 2018-01-02
    2 2018-01-03
    
    In [63]: df['day'] = df.date.dt.day
    
    In [64]: df['month'] = df.date.dt.month
    
    In [65]: df
    Out[65]:
            date  day  month
    0 2018-01-01    1      1
    1 2018-01-02    2      1
    2 2018-01-03    3      1
    

    Timing the methods provided:

    Using apply:

    In [217]: %timeit(df['date'].apply(lambda d: d.day))
    The slowest run took 33.66 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 210 µs per loop
    

    Using dt.date:

    In [218]: %timeit(df.date.dt.day)
    10000 loops, best of 3: 127 µs per loop
    

    Using dt.strftime:

    In [219]: %timeit(df.date.dt.strftime('%d'))
    The slowest run took 40.92 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 284 µs per loop
    

    We can see that dt.day is the fastest

提交回复
热议问题