Richard
Richard

Reputation: 65530

How do I fill NA values in multiple columns in pandas?

I have a dataframe with 50 columns. I want to replace NAs with 0 in 10 columns.

What's the simplest, most readable way of doing this?

I was hoping for something like:

cols = ['a', 'b', 'c', 'd']
df[cols].fillna(0, inplace=True)

But that gives me ValueError: Must pass DataFrame with boolean values only.

I found this answer, but it's rather hard to understand.

Upvotes: 6

Views: 34865

Answers (3)

Yannis P.
Yannis P.

Reputation: 2765

And a version using column slicing which might be useful in your case:

In [46]:
df

Out[46]:
    a   b   c   d   e
0   NaN NaN NaN 3   8
1   NaN NaN NaN 8   7
2   NaN NaN NaN 2   8
3   NaN NaN NaN 7   4
4   NaN NaN NaN 4   9
5   9   NaN NaN 1   9
6   NaN NaN NaN 7   7
7   NaN NaN NaN 6   5
8   NaN NaN NaN 0   0
9   NaN NaN NaN 9   5

In [47]:
df.loc[:,'a':'c'] = df.loc[:,'a':'c'].fillna(0)
df

Out[47]:
    a   b   c   d   e
0   0   0   0   3   8
1   0   0   0   8   7
2   0   0   0   2   8
3   0   0   0   7   4
4   0   0   0   4   9
5   9   0   0   1   9
6   0   0   0   7   7
7   0   0   0   6   5
8   0   0   0   0   0
9   0   0   0   9   5

Upvotes: 3

yaizer
yaizer

Reputation: 336

In [15]: cols= ['one', 'two']
In [16]: df
Out[16]:
        one       two     three four   five
a -0.343241  0.453029 -0.895119  bar  False
b       NaN       NaN       NaN  NaN    NaN
c  0.839174  0.229781 -1.244124  bar   True
d       NaN       NaN       NaN  NaN    NaN
e  1.300641 -1.797828  0.495313  bar   True
f -0.182505 -1.527464  0.712738  bar  False
g       NaN       NaN       NaN  NaN    NaN
h  0.626568 -0.971003  1.192831  bar   True

In [17]: df[cols]=df[cols].fillna(0)

In [18]: df
Out[18]:
        one       two     three four   five
a -0.343241  0.453029 -0.895119  bar  False
b  0.000000  0.000000       NaN  NaN    NaN
c  0.839174  0.229781 -1.244124  bar   True
d  0.000000  0.000000       NaN  NaN    NaN
e  1.300641 -1.797828  0.495313  bar   True
f -0.182505 -1.527464  0.712738  bar  False
g  0.000000  0.000000       NaN  NaN    NaN
h  0.626568 -0.971003  1.192831  bar   True

Upvotes: 11

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

you can use update():

In [145]: df
Out[145]:
    a   b   c  d  e
0 NaN NaN NaN  3  8
1 NaN NaN NaN  8  7
2 NaN NaN NaN  2  8
3 NaN NaN NaN  7  4
4 NaN NaN NaN  4  9
5 NaN NaN NaN  1  9
6 NaN NaN NaN  7  7
7 NaN NaN NaN  6  5
8 NaN NaN NaN  0  0
9 NaN NaN NaN  9  5

In [146]: df.update(df[['a','b','c']].fillna(0))

In [147]: df
Out[147]:
     a    b    c  d  e
0  0.0  0.0  0.0  3  8
1  0.0  0.0  0.0  8  7
2  0.0  0.0  0.0  2  8
3  0.0  0.0  0.0  7  4
4  0.0  0.0  0.0  4  9
5  0.0  0.0  0.0  1  9
6  0.0  0.0  0.0  7  7
7  0.0  0.0  0.0  6  5
8  0.0  0.0  0.0  0  0
9  0.0  0.0  0.0  9  5

Upvotes: 24

Related Questions