DataFrame按平台填充Critic_Score列NaN值失败问题求助
Hey there! Let's break down why your attempts to fill missing Critic_Score values with platform-specific means aren't working, and get this sorted out.
First, Let's Diagnose Each Attempt
Let's go through your 4 tries one by one to spot the issues:
Attempt 1: Mixing
inplace=Truewith assignment
Your code:x['Critic_Score'] = x['Critic_Score'].fillna(x.groupby('Platform')['Critic_Score'].transform('mean'), inplace = True)The problem here is that
inplace=Truemakes thefillna()method returnNone, and you're assigning thatNonedirectly to the column. That's why your output shows all values asNone. You should use eitherinplace=True(without assignment) or assign the result withoutinplace=True—not both.Attempts 2-4: Platforms with no valid scores
For the other three attempts, nothing changed for rows 1 (nes) and 4 (gb) because in your dataset subset, those platforms have no non-NaNCritic_Scorevalues. When you calculate the mean of a group that's entirely NaN, the result is also NaN—so you're trying to fill NaN with NaN, which does nothing.
The Fix
Here's how to properly handle this, covering both scenarios (platforms with valid scores, and platforms with all NaNs):
Step 1: Check platform-specific means first
First, verify which platforms have valid Critic_Score data to calculate a mean:
print(x.groupby('Platform')['Critic_Score'].mean())
This will show you which platforms have a numeric mean, and which are NaN (no valid scores).
Step 2: Fill with platform means, then handle remaining NaNs
We'll first fill missing values with their platform's mean (where possible), then fill any leftover NaNs with the global mean of Critic_Score (or another value of your choice):
# Fill with platform-specific means first x['Critic_Score'] = x.groupby('Platform')['Critic_Score'].transform( lambda group: group.fillna(group.mean()) ) # Fill any remaining NaNs (platforms with no valid scores) with global mean x['Critic_Score'] = x['Critic_Score'].fillna(x['Critic_Score'].mean())
Fixing Attempt 1 (if you want to use fillna directly)
If you prefer the fillna() approach, correct it by removing either the assignment or the inplace=True:
# Option 1: Use inplace without assignment x['Critic_Score'].fillna(x.groupby('Platform')['Critic_Score'].transform('mean'), inplace=True) # Option 2: Assign without inplace x['Critic_Score'] = x['Critic_Score'].fillna(x.groupby('Platform')['Critic_Score'].transform('mean'))
Just remember this still won't fill NaNs for platforms with no valid scores—you'll need the second step above for those.
Example with Your Sample Data
In your subset:
- The
wiiplatform has a mean of(76 + 82 + 80)/3 = 79.333...—any NaNs inwiirows would get filled with this value. nesandgbhave no valid scores, so their mean is NaN. After the first step, those rows stay NaN, then the second step fills them with the global mean of all non-NaNCritic_Scorevalues (which is79.333...in your subset).
内容的提问来源于stack exchange,提问作者Kushal Mohnot

