How can I Group By Month from a Date field using Python/Pandas

后端 未结 5 1920
孤独总比滥情好
孤独总比滥情好 2021-02-02 10:57

I have a Data-frame df which is as follows:

| date      | Revenue |
|-----------|---------|
| 6/2/2017  | 100     |
| 5/23/2017 | 200     |
| 5/20/2017 | 300             


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 11:17

    Try this:

    1. Chaged the date column into datetime formate.

      ---> df['Date'] = pd.to_datetime(df['Date'])

    2. Insert new row in data frame which have month like->[May, 'June']

      ---> df['months'] = df['date'].apply(lambda x:x.strftime('%B'))

      ---> here x is date which take from date column in data frame.

    3. Now aggregate aggregate data on month column and sum the revenue.

      --->response_data_frame = df.groupby('months')['Revenue'].sum()

      ---->print(response_data_frame)

    output -:

    | month | Revenue |
    
    |-------|---------|
    
    | May   | 500     |
    
    | June  | 1000    |
    

提交回复
热议问题