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

如何使用Pandas创建透视表,按年份获取计数最高的姓名及对应计数值?

How to Get Top Name and Max Count per Year with 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 and max on 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 max on both Name and Count doesn't work because max for 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:32:47