Using fillna method on multiple Pandas DataFrame columns fails
Why did this operation fail? For example:
a = pd.DataFrame({'a': [1,2,np.nan, np.nan],
'b': [5,np.nan,6, np.nan],
'c': [5, 1, 5, 2]})
a[['a', 'b']].fillna(0, inplace=True)
and gave me this warning:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
But it a
was still filling up NA
as before. However, if I call .fillna()
for each column separately, there is no problem. How can I fill in values NA
for multiple columns in one shot?
+3
source to share
2 answers
Option 1
a.loc[:, ['a', 'b']] = a[['a', 'b']].fillna(0)
print(a)
a b c
0 1.0 5.0 5
1 2.0 0.0 1
2 0.0 6.0 5
3 0.0 0.0 2
Option 2
a.update(a[['a', 'b']].fillna(0))
print(a)
a b c
0 1.0 5.0 5
1 2.0 0.0 1
2 0.0 6.0 5
3 0.0 0.0 2
Option 3
for col in ['a', 'b']:
a[col].fillna(0, inplace=True)
print(a)
a b c
0 1.0 5.0 5
1 2.0 0.0 1
2 0.0 6.0 5
3 0.0 0.0 2
Option 4
a.fillna(a[['a', 'b']].fillna(0), inplace=True)
print(a)
a b c
0 1.0 5.0 5
1 2.0 0.0 1
2 0.0 6.0 5
3 0.0 0.0 2
+3
source to share