Extracting just Month and Year separately from Pandas Datetime column

后端 未结 11 1755
抹茶落季
抹茶落季 2020-11-22 09:09

I have a Dataframe, df, with the following column:

df[\'ArrivalDate\'] =
...
936   2012-12-31
938   2012-12-29
965   2012-12-31
966   2012-12-31
967   2012-1         


        
11条回答
  •  一向
    一向 (楼主)
    2020-11-22 09:45

    @KieranPC's solution is the correct approach for Pandas, but is not easily extendible for arbitrary attributes. For this, you can use getattr within a generator comprehension and combine using pd.concat:

    # input data
    list_of_dates = ['2012-12-31', '2012-12-29', '2012-12-30']
    df = pd.DataFrame({'ArrivalDate': pd.to_datetime(list_of_dates)})
    
    # define list of attributes required    
    L = ['year', 'month', 'day', 'dayofweek', 'dayofyear', 'weekofyear', 'quarter']
    
    # define generator expression of series, one for each attribute
    date_gen = (getattr(df['ArrivalDate'].dt, i).rename(i) for i in L)
    
    # concatenate results and join to original dataframe
    df = df.join(pd.concat(date_gen, axis=1))
    
    print(df)
    
      ArrivalDate  year  month  day  dayofweek  dayofyear  weekofyear  quarter
    0  2012-12-31  2012     12   31          0        366           1        4
    1  2012-12-29  2012     12   29          5        364          52        4
    2  2012-12-30  2012     12   30          6        365          52        4
    

提交回复
热议问题