Pandas按日期分组,按标签数量占优计算对应分数总和的实现咨询
按日期分组统计标签数量并计算占优标签分数总和
原始数据
首先修正日期格式问题(原代码中直接写2020-12-30会被计算为数值,需转为datetime类型):
import pandas as pd test = pd.DataFrame({ 'Date': pd.to_datetime(['2020-12-30', '2020-12-30', '2020-12-30', '2020-12-31', '2020-12-31', '2021-01-01', '2021-01-01']), 'label': ['Positive', 'Positive', 'Negative', 'Negative','Negative', 'Positive', 'Positive'], 'score': [70, 80, 50, 50, 30, 90, 70] })
数据展示:
Date label score 0 2020-12-30 Positive 70 1 2020-12-30 Positive 80 2 2020-12-30 Negative 50 3 2020-12-31 Negative 50 4 2020-12-31 Negative 30 5 2021-01-01 Positive 90 6 2021-01-01 Positive 70
需求
- 按
Date分组,统计每日Positive和Negative标签的数量 - 计算当日数量占优标签的
score总和(数量多的标签分数相加)
尝试过的代码
new_df = test.groupby(['Date', 'label']).agg({'label' : 'count', 'score' : 'mean'})
期望输出
Date label new_score count_pos count_neg 0 2020-12-30 Positive 150 2 1 1 2020-12-31 Negative 80 0 2 2 2021-01-01 Positive 160 2 0
字段说明:
new_score:当日数量占优标签的score总和count_pos:当日Positive标签的数量count_neg:当日Negative标签的数量
解决方案
步骤1:分组统计标签数量与分数总和
先按Date和label分组,计算每组的标签数量和分数总和:
grouped = test.groupby(['Date', 'label']).agg( count=('label', 'count'), total_score=('score', 'sum') ).reset_index()
得到的中间结果:
Date label count total_score 0 2020-12-30 Negative 1 50 1 2020-12-30 Positive 2 150 2 2020-12-31 Negative 2 80 3 2021-01-01 Positive 2 160
步骤2:转换为宽表统计每日标签数量
将label的数量转为count_pos和count_neg列,方便后续合并:
count_pivot = grouped.pivot( index='Date', columns='label', values='count' ).fillna(0).astype(int).rename(columns={ 'Positive': 'count_pos', 'Negative': 'count_neg' }).reset_index()
结果:
Date count_neg count_pos 0 2020-12-30 1 2 1 2020-12-31 2 0 2 2021-01-01 0 2
步骤3:筛选占优标签并合并数据
标记每组是否为当日数量最多的标签,筛选出占优标签的行,再与宽表合并:
# 标记当日数量最多的标签 grouped['is_max'] = grouped.groupby('Date')['count'].transform(lambda x: x == x.max()) # 筛选占优标签的行 dominant = grouped[grouped['is_max']].drop(columns='is_max') # 合并数据并调整列顺序 final_df = pd.merge(dominant, count_pivot, on='Date').rename(columns={'total_score': 'new_score'}) final_df = final_df[['Date', 'label', 'new_score', 'count_pos', 'count_neg']]
完整代码
import pandas as pd # 初始化数据 test = pd.DataFrame({ 'Date': pd.to_datetime(['2020-12-30', '2020-12-30', '2020-12-30', '2020-12-31', '2020-12-31', '2021-01-01', '2021-01-01']), 'label': ['Positive', 'Positive', 'Negative', 'Negative','Negative', 'Positive', 'Positive'], 'score': [70, 80, 50, 50, 30, 90, 70] }) # 分组统计数量和分数总和 grouped = test.groupby(['Date', 'label']).agg( count=('label', 'count'), total_score=('score', 'sum') ).reset_index() # 转宽表统计每日标签数量 count_pivot = grouped.pivot( index='Date', columns='label', values='count' ).fillna(0).astype(int).rename(columns={ 'Positive': 'count_pos', 'Negative': 'count_neg' }).reset_index() # 筛选占优标签并合并 grouped['is_max'] = grouped.groupby('Date')['count'].transform(lambda x: x == x.max()) dominant = grouped[grouped['is_max']].drop(columns='is_max') final_df = pd.merge(dominant, count_pivot, on='Date').rename(columns={'total_score': 'new_score'}) final_df = final_df[['Date', 'label', 'new_score', 'count_pos', 'count_neg']] print(final_df)
运行后即可得到期望的输出结果。
内容的提问来源于stack exchange,提问作者Laurence Bach
相关产品推荐
相关产品推荐

