【问题标题】:Groupby and count in Pandas在 Pandas 中分组和计数
【发布时间】:2021-12-27 12:27:12
【问题描述】:

我必须对 col1、col2 和 loc 的以下数据进行分组,并计算 col3 中的项目数。此外,要考虑的是开始和结束日期,即日期应介于 2021 年 1 月 1 日至 2021 年 1 月 31 日之间。最终结果应该显示在 col4 中。

数据

Date        col1        col2        loc     col3    
01/01/2021  India       Fruits        A     Mango
04/01/2021  India       Fruits        A     Apple
08/01/2021  India       Fruits        A     Banana  
09/01/2021  India       Vegetables    B     Onion
07/01/2021  India       Vegetables    B     Capsicum
02/02/2021  India       Vegetables    B     Tomato
03/01/2021  Germany     Fruits        C     Mango
19/01/2021  Germany     Fruits        C     Apple
28/01/2021  Germany     Fruits        C     Banana  
29/01/2021  Germany     Vegetables    D     Onion
07/02/2021  Germany     Vegetables    D     Capsicum
02/01/2021  Germany     Vegetables    D     Tomato

预期输出

Date        col1        col2        loc      col3          col4
01/01/2021  India       Fruits      A        Mango          3
04/01/2021  India       Fruits      A        Apple          3
08/01/2021  India       Fruits      A        Banana         3
09/01/2021  India       Vegetables  B        Onion          2
07/01/2021  India       Vegetables  B        Capsicum       2
03/01/2021  Germany     Fruits      C        Mango          3
19/01/2021  Germany     Fruits      C        Apple          3
28/01/2021  Germany     Fruits      C        Banana         3
29/01/2021  Germany     Vegetables  D        Onion          2
02/01/2021  Germany     Vegetables  D        Tomato         2

【问题讨论】:

  • 如果不匹配,行会发生什么?计数是像0 还是被删除?
  • 它必须被删除

标签: python pandas date count pandas-groupby


【解决方案1】:

使用Series.between 按日期时间过滤,然后使用GroupBy.transform

m = pd.to_datetime(df['Date'], dayfirst=True).between('2021-01-01', '2021-01-31')

df1 = df[m].copy()
df1['col4'] = df1.groupby(['col1','col2','loc'])['col3'].transform('size')

如果需要计数而不删除:

df['col4'] = (df.assign(col3 = df['col3'].where(m))
                .groupby(['col1','col2','loc'])['col3']
                .transform('count'))
print (df)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 2015-07-27
    • 2017-08-11
    • 2014-06-17
    • 2018-04-10
    • 2020-02-13
    • 2018-10-02
    • 1970-01-01
    相关资源
    最近更新 更多