Extracting just Month and Year separately from Pandas Datetime column

后端 未结 11 1778
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    2020-11-22 09:35

    SINGLE LINE: Adding a column with 'year-month'-paires: ('pd.to_datetime' first changes the column dtype to date-time before the operation)

    df['yyyy-mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y-%m')

    

    Accordingly for an extra 'year' or 'month' column:

    df['yyyy'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y')

    df['mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%m')

    

提交回复
热议问题