You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按多列分组计数并按指定日期范围过滤的实现方法

数据处理需求说明

本次需要完成的操作如下:

  • 过滤有效数据:仅保留日期范围为2021年1月1日至2021年1月31日的记录
  • 分组统计规则:按col1、col2、loc三列分组,统计每个分组下col3的条目数量
  • 结果输出要求:统计得到的数量新增为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

实现代码(Python Pandas)

import pandas as pd

# 读取数据,可根据实际存储格式调整读取方法
df = pd.read_csv("数据文件路径.csv", parse_dates=["Date"], dayfirst=True)

# 过滤2021年1月的有效数据
df_filter = df[(df["Date"] >= "2021-01-01") & (df["Date"] <= "2021-01-31")].copy()

# 分组统计并新增col4列
df_filter["col4"] = df_filter.groupby(["col1", "col2", "loc"])["col3"].transform("count")

# 查看结果
print(df_filter)

内容的提问来源于stack exchange,提问作者Nithya Babu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:06:01