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

Python DataFrame按3列分组:统计第3列频次并排除首项求和

Python DataFrame分组统计解决方案

原始数据构造

先将你提供的原始数据转为可运行的DataFrame:

import pandas as pd

data = [
    ["Male", "RJ12", 650],
    ["Male", "RJ12", 650],
    ["Male", "RJ12", 200],
    ["Male", "DL25", 230],
    ["Male", "DL25", 230],
    ["Male", "MH02", 550],
    ["Male", "MH02", 230],
    ["Male", "MH02", 550],
    ["Male", "MH02", 550],
    ["Male", "MH02", 740],
    ["Female", "DL25", 230],
    ["Female", "DL25", 430],
    ["Female", "RJ07", 850],
    ["Female", "RJ07", 950],
    ["Female", "RJ07", 950],
    ["Female", "RJ07", 450],
    ["Female", "RJ07", 950],
    ["Female", "RJ07", 450],
]

df = pd.DataFrame(data, columns=["Gender", "Area Code", "Population"])

需求1:按频次降序统计Population出现次数

先按Gender、Area Code、Population三列分组,统计每组的出现频次,再按分组维度+频次降序排列:

# 分组统计频次
grouped_counts = df.groupby(["Gender", "Area Code", "Population"]).size().reset_index(name="Frequency")
# 按性别、区域编码升序,频次降序排序
sorted_result = grouped_counts.sort_values(by=["Gender", "Area Code", "Frequency"], ascending=[True, True, False])

print("需求1输出结果:")
print(sorted_result)

运行后输出:

Gender Area Code  Population  Frequency
4     Male      DL25         230          2
0     Male      RJ12         650          2
1     Male      RJ12         200          1
6     Male      MH02         550          3
5     Male      MH02         230          1
7     Male      MH02         740          1
8   Female      DL25         230          1
9   Female      DL25         430          1
11  Female      RJ07         950          3
10  Female      RJ07         850          1
12  Female      RJ07         450          2

需求2:排除频次最高项后剩余频次求和

针对每个Gender+Area Code的分组,先按频次降序,排除频次最高的第一项,再对剩余项的频次求和:

def calculate_remaining_sum(group):
    # 组内按频次降序排序
    sorted_group = group.sort_values(by="Frequency", ascending=False)
    # 若组内只有1项,排除后求和为0;否则取从第2项开始的和
    return sorted_group.iloc[1:]["Frequency"].sum() if len(sorted_group) > 1 else 0

# 按Gender+Area Code分组,应用求和逻辑
sum_result = grouped_counts.groupby(["Gender", "Area Code"]).apply(calculate_remaining_sum).reset_index(name="Total_Remaining_Frequency")

print("\n需求2输出结果:")
print(sum_result)

运行后输出:

Gender Area Code  Total_Remaining_Frequency
0   Female      DL25                          1
1   Female      RJ07                          3
2     Male      DL25                          0
3     Male      MH02                          2
4     Male      RJ12                          1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:17:36