我想总结美国,中国和日本的能源价值,并把这个“group1”标签,然后分组按日期,国家,类型和总和的能源价值。
数据
我们将按日期分组,输入并取这些特定国家的总和:美国、中国和日本--将这个组合重新命名为group1。
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期望的
date country type energy
8/1/2022 group1 aa 21
8/1/2022 group1 bb 70
10/1/2022 Australia bb 5做
df.groupby(['country','date', 'type'], as_index=False).agg({'energy': sum})上面的脚本完美地执行了groupby和sum,但不确定在执行此步骤之前如何将某些类别压缩到组中。
如有任何建议,将不胜感激。
发布于 2022-11-03 16:49:46
如果您想将它们组合起来,不如先过滤,然后将值更改为group1,然后执行groupby操作如何?
df.loc[df['country'].isin(['US', 'China', 'Japan']), 'country'] = 'group1'
df.groupby(['date', 'type', 'country'], as_index=False, sort=False).agg({'energy': sum}) date type country energy
0 8/1/2022 aa group1 21
1 8/1/2022 bb group1 70
2 10/1/2022 bb Australia 5发布于 2022-11-03 16:53:03
# define a dictionary to group the countries
d={'US': 'Group-1',
'China':'Group-1',
'Japan' :'Group-1'}
# create a group column, based on mapping
# keeping a separate column, to avoid losing original values
# it can very well be a country
df['group']=df['country'].map(d).fillna(df['country'])
# do a groupby
out= df.groupby(['group','date', 'type'], as_index=False).agg({'energy': sum}) group date type energy
0 Australia 10/1/2022 bb 5
1 Group-1 8/1/2022 aa 21
2 Group-1 8/1/2022 bb 70https://stackoverflow.com/questions/74306713
复制相似问题