Hatim
Hatim

Reputation: 31

How do I .apply or .replace multiple columns at once in pandas?

The code below works..

df['Forecast'] = df['Forecast'].apply(lambda x: '0' if x == '' else x)

df['Yield'] = df['Yield'].apply(lambda x: '0' if x == '' else x)

but when I try to do together, it doesn't work

to_change = ['Forecast', 'Yield']

df[to_change] = df[to_change].apply(lambda x: '0' if x == '' else x)

it gives the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

How to perform these functions (replace or apply) together at once without writing a new code line for every column?

Upvotes: 1

Views: 1151

Answers (1)

keepAlive
keepAlive

Reputation: 6655

What about using pandas.DataFrame.replace ?

to_change     = ['Forecast', 'Yield']
df[to_change] = df[to_change].replace(to_replace='', value='0')
#            or df[to_change].replace({'': '0'})

tested.


An illustration. Say you have df defined as follows

df = pd.DataFrame({
    '_else_'  : ['', '', ''],
    'Forecast': ['', 'y', 'o'],
    'Yield'   : ['k', '', 'm'],
})

i.e.

>>> df
  _else_ Forecast Yield
0                     k
1               y      
2               o     m

It turns out that doing

>>> df[to_change] = df[to_change].replace({'': '0'})

has changed df as follows

>>> df
  _else_ Forecast Yield
0               0     k
1               y     0
2               o     m

Upvotes: 1

Related Questions