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

Dataframe二级索引排序与前n项求和,按州分组人口降序排序

Got it, let's work through these two pandas tasks using your sample dataset. First, let's initialize the DataFrame so we can test the code directly:

import pandas as pd

# Your sample data
data = {
    'Population2010': [90332, 92082, 52000, 3879602, 4364594, 12123562, 161818, 737728, 222368, 2239378, 448888, 1000564],
    'State': ['AL', 'AL', 'AL', 'CA', 'CA', 'CA', 'CO', 'CO', 'CO', 'AZ', 'AZ', 'AZ'],
    'County': ['Baldwin', 'Douglas', 'Rolling', 'Orange', 'San Diego', 'Los Angeles', 'Boulder', 'Denver', 'Jefferson', 'Maricopa', 'Pinal', 'Pima']
}

df = pd.DataFrame(data)
需求1:对二级索引排序并求和取前n条目

First, we'll set up a multi-index with State as the first level and County as the second. Then we'll sort the second index, calculate total population per state, and finally pick the top n states by their total population.

Here's the code:

# Step 1: Set up multi-index (State = level 0, County = level 1)
df_multi = df.set_index(['State', 'County'])

# Step 2: Sort by the second index (County name, ascending order by default)
df_sorted_index = df_multi.sort_index(level='County')

# Step 3: Calculate total population for each state
state_pop_totals = df_sorted_index.groupby(level='State').sum()

# Step 4: Sort totals descending and pick top n (replace n with your desired number, e.g., 2)
n = 2
top_n_states = state_pop_totals.sort_values('Population2010', ascending=False).head(n)

print(top_n_states)

Output for n=2:

Population2010
State                  
CA             20367758
AZ              3688830

If you meant sorting the second index by population (instead of county name), just adjust step 2 to sort by the Population2010 column within each state—let me know if you need that tweak!

需求2:按州分组后组内按Population2010降序排序

There are two simple ways to handle this. The first sorts the entire DataFrame directly, while the second uses groupby to explicitly sort each state's subgroup.

Method 1: Direct sort (most straightforward)

# Sort by State (ascending) and Population2010 (descending)
df_sorted = df.sort_values(['State', 'Population2010'], ascending=[True, False])

print(df_sorted)

Output:

Population2010 State       County
1            92082    AL      Douglas
0            90332    AL      Baldwin
2            52000    AL      Rolling
5         12123562    CA  Los Angeles
4          4364594    CA    San Diego
3          3879602    CA       Orange
7           737728    CO       Denver
8           222368    CO    Jefferson
6           161818    CO      Boulder
9          2239378    AZ     Maricopa
11         1000564    AZ         Pima
10          448888    AZ        Pinal

Method 2: Groupby + apply (explicit subgroup sorting)

Use this if you want to process each state's group separately before sorting:

# Group by State, sort each group by population descending, then reset index
df_group_sorted = df.groupby('State', group_keys=False).apply(lambda x: x.sort_values('Population2010', ascending=False)).reset_index(drop=True)

print(df_group_sorted)

This gives the same output as Method 1, with group_keys=False ensuring we don't add extra index columns from the grouping.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:17:38