我可以在 excel 中执行此操作,但我正在寻找一种在 python 中执行此操作的方法。你知道做以下事情的方法吗
初始
District_1 District_2 District_3
Food 69 47 65
Water 87 86 32
Shelter 63 84 27
映射
District_1 London
District_2 London
District_3 Boston
想要的
London Boston
Food 116 65
Water 173 32
Shelter 147 27
请您参考如下方法:
我假设你的映射是一个字典
mapping = {'District_1': 'London', 'District_2': 'London', 'District_3': 'Boston'}
然后使用 groupby 和 axis=1
df.groupby(mapping, axis=1).sum()
Boston London
Food 65 116
Water 32 173
Shelter 27 147
当您将字典传递给 groupby 时,它的 get 方法会应用于选择的轴(默认情况下轴 = 0),结果定义组。
