groupby操作后按月份对数据帧进行排序

2024-04-24 23:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的数据示例:

   Date        Count
11.01.2019       1  
01.02.2019       7  
25.01.2019       4  
23.01.2019       4  
16.03.2019       1  
04.02.2019       5
06.04.2019       1  
04.04.2019       5

所需输出:

Month  Total_Count
Jan        9
Feb       12
Mar        1
Apr        6

对于上面的总结操作,我使用了下面的代码,它工作得很好,但是月份都很混乱,没有像一月、二月那样进行相应的排序

(df.groupby(pd.to_datetime(df['Date'], format='%d.%m.%Y')
   .dt.month_name()
   .str[:3])['Count']
   .sum()
   .rename_axis('Month')
   .reset_index(name='Total_Count'))

Tags: 数据代码name示例dfdate排序count
2条回答

想法是将列转换为日期时间,然后使用sort=False进行排序和分组,以避免groupby中的默认排序:

df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
df1 = (df.sort_values('Date')
         .groupby(df['Date'].dt.month_name().str[:3], sort=False)['Count']
         .sum()
         .rename_axis('Month')
         .reset_index(name='Total_Count'))
print (df1)
  Month  Total_Count
0   Jan            9
1   Feb           12
2   Mar            1
3   Apr            6

另一个想法是,谢谢anky,使用有序的Categorical,然后需要删除sort=False

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df1 = (df.groupby(pd.Categorical(pd.to_datetime(df['Date'], format='%d.%m.%Y')
         .dt.month_name().str[:3],ordered=True,categories=months))['Count']
         .sum()
         .rename_axis('Month')
         .reset_index(name='Total_Count'))

或使用^{}

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

df1 = (df.groupby(pd.to_datetime(df['Date'], format='%d.%m.%Y')
         .dt.month_name().str[:3])['Count']
         .sum()
         .rename_axis('Month')
         .reindex(months, fill_value=0)
         .reset_index(name='Total_Count'))

print (df1)
   Month  Total_Count
0    Jan            9
1    Feb           12
2    Mar            1
3    Apr            6
4    May            0
5    Jun            0
6    Jul            0
7    Aug            0
8    Sep            0
9    Oct            0
10   Nov            0
11   Dec            0

试试这个:

new_df = (df.sort_values('Date')
     .groupby(df['Date'].dt.month_name().str[:3], sort=False)['Count']
     .sum()
     .rename_axis('Month')
     .reset_index(name='Total_Count'))
print(new_df)

相关问题 更多 >