Extracting the first day of month of a datetime type column in pandas

前端 未结 8 1191
你的背包
你的背包 2020-12-14 06:11

I have the following dataframe:

user_id    purchase_date 
  1        2015-01-23 14:05:21
  2        2015-02-05 05:07:30
  3        2015-02-18 17:08:51
  4            


        
8条回答
  •  抹茶落季
    2020-12-14 06:31

    Try this ..

    df['month']=pd.to_datetime(df.purchase_date.astype(str).str[0:7]+'-01')
    
    Out[187]: 
       user_id        purchase_date       month
    0        1  2015-01-23 14:05:21  2015-01-01
    1        2  2015-02-05 05:07:30  2015-02-01
    2        3  2015-02-18 17:08:51  2015-02-01
    3        4  2015-03-21 17:07:30  2015-03-01
    4        5  2015-03-11 18:32:56  2015-03-01
    5        6  2015-03-03 11:02:30  2015-03-01
    

提交回复
热议问题