gpt4 book ai didi

python - Pandas 按总和分组仅保留索引之一作为列

转载 作者:行者123 更新时间:2023-11-30 22:58:11 26 4
gpt4 key购买 nike

我有一个如下所示的数据框:

import pandas as pd
group = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']
df = {'population': [100,200,300,400,500,600,700,800],
'city_name': ['Chicago', 'Chicago', 'New York', 'New York', 'Chicago', 'New York', 'Chicago', 'New York'],
}
df = pd.DataFrame(df, index=group)


city_name population
A Chicago 100
A Chicago 200
A New York 300
A New York 400
B Chicago 500
B New York 600
B Chicago 700
B New York 800

现在我想找到按索引和city_name分组的总人口,很简单:

total = df.groupby([df.index, 'city_name']).sum()

population
city_name
A Chicago 300
New York 700
B Chicago 1200
New York 1400

问题是这会返回一个多级索引(我认为)。我想要的是保留原始索引,但将 city_name 保留为列。换句话说,我想要的是

    city_name     population
A Chicago 300
A New York 700
B Chicago 1200
B New York 1400

现在我可以通过做类似的事情来实现我想要的东西

total.reset_index(inplace=True)
total.set_index(keys='level_0', inplace=True)

由于reset_index接受两个索引并将它们作为列,然后我可以将其中一个设置回索引。有没有更优雅的方法来做到这一点?

谢谢!

最佳答案

我认为您需要将参数level=1添加到reset_index仅重置 multiindex 的第二级:

total.reset_index(level=1, inplace=True)
print total
city_name population
A Chicago 300
A New York 700
B Chicago 1200
B New York 1400

或者:

total.reset_index(level='city_name', inplace=True)
print total
city_name population
A Chicago 300
A New York 700
B Chicago 1200
B New York 1400

关于python - Pandas 按总和分组仅保留索引之一作为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36300577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com