【问题标题】:Need to group the data using pandas based on months in the column data需要使用 pandas 根据列数据中的月份对数据进行分组
【发布时间】:2020-04-24 14:54:04
【问题描述】:

我想根据 1 月和 2 月对数据进行分组。这是我拥有的数据集的示例。

   Date       Count

01.01.2019       1  
01.02.2019       7  
02.01.2019       4  
03.01.2019       4  
04.01.2019       1  
04.02.2019       5

我想将数据分组如下,其中总计数是基于第 1 个月(1 月)和 2(2 月)的计数相加:

Month  Total_Count
Jan       10
Feb       12

【问题讨论】:

  • 不,它没有。对此我很抱歉

标签: python pandas datatables dataset pandas-groupby


【解决方案1】:

转换为日期时间,按dt.month_namesum 分组:

(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'))

  Month  Total_Count
0   Feb           12
1   Jan           10

要按月对索引进行排序,我们可以这样做:

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

  Month  Total_Count
0   Jan           10
1   Feb           12

【讨论】:

  • 不客气@VishvamNaik 不要忘记您可以投票并接受答案。见What should I do when someone answers my question?,谢谢!
  • 我对这个@yatu 有点怀疑。如何通过在进一步的代码中调用它来向这个数据框添加一列?
  • 如果可以更好地避免它,@vishvam 通常不是一个好习惯。最好的方法是只计算一次,仅此而已。附加到 df 不是一个好主意。
猜你喜欢
  • 2017-10-09
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多