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

如何用Pandas将中美日合并为group1后按日期、国家、类型分组求和?

合并指定国家分组并实现求和

需求说明

  • 将美国(US)、中国(China)、日本(Japan)的energy值合并后标记为group1
  • 最终按date、country、type分组对energy值求和

原始数据

date        country    type energy
8/1/2022    US         aa   10
8/1/2022    US         aa   11
8/1/2022    China      bb   50
8/1/2022    Japan      bb   20
10/1/2022   Australia  bb   5

当前代码问题

现有代码仅能完成常规分组求和,但无法提前将指定国家合并为group1:

df.groupby(['country','date', 'type'], as_index=False).agg({'energy': sum})

解决方案

先对country列进行替换处理,再执行分组求和:

步骤1:替换指定国家为group1

可以用两种方式实现替换:

方式一:使用numpy.where

import numpy as np
import pandas as pd

# 将目标国家统一替换为group1,其余国家保持不变
df['country'] = np.where(df['country'].isin(['US', 'China', 'Japan']), 'group1', df['country'])

方式二:使用pandas.replace

# 逐个映射目标国家到group1
df['country'] = df['country'].replace({'US': 'group1', 'China': 'group1', 'Japan': 'group1'})

步骤2:执行分组求和

替换完成后,按date、country、type的顺序分组求和:

result = df.groupby(['date', 'country', 'type'], as_index=False).agg({'energy': 'sum'})

最终结果

date        country   type  energy
8/1/2022    group1    aa    21
8/1/2022    group1    bb    70
10/1/2022   Australia bb    5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:45:37