Pandas dataframe fillna() only some columns in place
Fill specific columns' NaNs in-place applying this simple rule:
It targets col1
and col2
NaNs, cozying them up with new friends: val1
and val2
.
Look ma, no inplace!
inplace=True
sounds awesome, but it can cause a mess in the sandpit - yep, irreversible changes. Try this neat trick instead:
Fills col1
and col2
NaNs with zeros, keeps other toys (columns) intact.
Preserving data: The secret sauce
For the Data-Integrity Chefs out there, back up before changing things. When not using inplace
, you can actually preview what's cooking:
Custom fillna values: NaNs are picky eaters
For NaNs, one size does not fit all. Numeric NaNs don't enjoy being a boring string, nor vice versa. Coddle them with the right diet:
Dodging bullets: Avoid SettingWithCopyWarning
The pesky SettingWithCopyWarning
is trigger happy when changing DataFrame copy instead of the original. Dodge this:
Remember: Be the Matrix, be the DataFrame.
No Metaphor Zone
Applying .fillna()
selectively == custom-made spanners for each missing bolt in the DataFrame-Engine.
MULTIPLE columns, too:
Before: Fast bolt <=> Spanner (Match! 🔨),
Missing bolt 🛠 (Better luck next time)
After: Fast Bolt <=> Spanner (Nice!🔨), Missing Bolt <=> New spanner (Nailed it!🔧)
Assignment: The Picasso of Pandas
Paint your DataFrame with direct assignments instead of inplace
splatters. The art here: easy undo, easy viewing.
Text data: NaNs don't enjoy being called '0'
Strings and categoricals squirm at numeric fill values. Serenade them with suitable string-fillers:
Because, every NaN is unique.. 😊
Was this article helpful?