如何使用Pandas创建透视表,按年份获取计数最高的姓名及对应计数值?
Hey there! Let's figure out how to get the top name and its count per year—you're close, just need to adjust your approach a bit.
Why Your Previous Code Didn't Work
Your goal is to get the name with the highest count for each year, but your existing code misses this core requirement:
- Code Example 1: The pivot table uses
['Year','Name']as the index andmaxon Count. This gives you the maximum count for each name per year (if a name appears multiple times in a year), not the name with the overall highest count for the year. - Code Example 2: Using
maxon bothNameandCountdoesn't work becausemaxfor strings uses lexicographical order (e.g., a name starting with "Z" would be considered "max" regardless of its count), which has no relation to the highest count value.
Fixes & Solutions
First, let's fix the data type issue: your line bn['Count'].astype(int) doesn't modify the original DataFrame—you need to assign the result back:
bn['Count'] = bn['Count'].astype(int)
Now here are two straightforward ways to achieve your desired output:
Method 1: groupby + idxmax (Most Efficient)
idxmax() returns the index of the row with the highest Count value for each year. We then use loc to extract those rows:
import pandas as pd # Load data bn = pd.read_csv("baby_names.csv") # Correct Count column type bn['Count'] = bn['Count'].astype(int) # Get indices of rows with max Count per Year max_count_indices = bn.groupby('Year')['Count'].idxmax() # Extract the relevant rows and columns top_names = bn.loc[max_count_indices, ['Year', 'Name', 'Count']].reset_index(drop=True) print(top_names)
Method 2: groupby + Custom Function (Flexible for Edge Cases)
If multiple names share the highest count in a year, this method lets you handle them (e.g., return the first one, or all of them):
import pandas as pd bn = pd.read_csv("baby_names.csv") bn['Count'] = bn['Count'].astype(int) def get_top_name(group): # Filter rows where Count equals the max for the year max_rows = group[group['Count'] == group['Count'].max()] # Return the first result (replace with `return max_rows` to keep all ties) return max_rows[['Name', 'Count']].iloc[0] top_names = bn.groupby('Year').apply(get_top_name).reset_index() print(top_names)
Both methods will produce output in your desired format, with each row showing the year, the top name, and its count.
内容的提问来源于stack exchange,提问作者DataMonkey

