Pandas如何提取分组后Rank为1的Points值并求和
Got it, let's walk through this step by step. First, let's recap the initial setup to make sure we're on the same page:
import pandas as pd ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'Kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pd.DataFrame(ipl_data) # First, get the grouped sum you mentioned grouped_df = df.groupby(['Team', 'Rank']).sum()
After running groupby(['Team', 'Rank']).sum(), you'll have a multi-index DataFrame where each row is unique to a Team-Rank pair, with the summed Points. Now we need to pull out all rows where Rank is 1, then sum their Points values.
Method 1: Using .loc with Multi-Index
Since we have a multi-index (Team and Rank), we can use .loc to slice all Teams where Rank equals 1:
# Select all Teams, Rank=1, and the Points column rank1_points = grouped_df.loc[(slice(None), 1), 'Points'] # Sum those values total_rank1_points = rank1_points.sum() print(total_rank1_points) # Output: 3224
The slice(None) here means "all values in the first index level (Team)", so we're grabbing every row where the second index (Rank) is 1.
Method 2: Reset Index and Filter
If you prefer working with regular columns instead of multi-indexes, reset the index first to make Team and Rank into regular columns, then filter:
# Reset index to turn Team and Rank into columns grouped_reset = grouped_df.reset_index() # Filter rows where Rank is 1, then get the Points column rank1_points = grouped_reset[grouped_reset['Rank'] == 1]['Points'] # Sum the values total_rank1_points = rank1_points.sum() print(total_rank1_points) # Output: 3224
Method 3: One-Liner (Combined)
You can also condense this into a single line if you want:
total_rank1_points = df.groupby(['Team', 'Rank']).sum().loc[(slice(None), 1), 'Points'].sum()
All these methods will give you the total sum of Points where Rank is 1, which is 3224 (876 from Riders + 1544 from Kings + 804 from Royals).
内容的提问来源于stack exchange,提问作者Merlin

