我尝试按照此处的示例进行我认为应该有效的操作。我想获取按
'Continent'
分组的所有数据,然后将其设置为我的索引。我尝试对数据进行分组:
cont.head()
Country Continent Population
0 China Asia 1367.645161
1 United States North America 317.615385
2 Japan Asia 127.409396
3 United Kingdom Europe 63.870968
4 Russian Federation Europe 143.500000
cont = cont.groupby('Continent')
cont
但我不断得到这个结果而不是实际分组的 DataFrame
<pandas.core.groupby.generic.DataFrameGroupBy object at 0x7f7ab3ae6ee0>
我怎样才能正确编写代码来制作索引
'Continent'
并使其余数据按每个大陆分组?
您正在寻找
set_index
。
cont = cont.set_index('Continent').sort_index()
额外的
sort_index
会在索引重复时折叠索引显示。
groupby
更适合聚合或循环操作,例如:
# looping
for continent, gdf in cont.groupby('continent'):
do_something(gdf)
# aggregation
populations = cont.groupby('continent')['population'].sum()