Using lambda with .apply() in Pandas

Viewed 124

In Pandas, I am trying to apply this lambda function, using .apply() and I am getting this error: 'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()'.

What am I doing wrong?

(beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')

beers is a series.

Thanks!

2 Answers

beers is not a Series else you code work well. It's certainly a DataFrame and probably a DataFrame with only one column.

Demo:

>>> beers = pd.Series(np.random.randint(1, 10, 20))

>>> type(beers)
pandas.core.series.Series

>>> (beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')
0    high
1     low
2    high
3     low
4    high
5    high
6     low
7    high
8    high
9     low
dtype: object

Now if beers is a DataFrame:

>>> beers = beers.to_frame()

>>> type(beers)
pandas.core.frame.DataFrame

>>> (beers[:10] - beers.mean()).apply(lambda x: 'low' if x < 0 else 'high')
...
ValueError: The truth value of a Series is ambiguous.
Use a.empty, a.bool(), a.item(), a.any() or a.all().

In the case where beers has only one column, you can use squeeze:

>>> (beers[:10] - beers.mean()).squeeze().apply(lambda x: 'low' if x < 0 else 'high')
0    high
1     low
2    high
3     low
4    high
5    high
6     low
7    high
8    high
9     low
Name: 0, dtype: object

I think what you are trying to do is this if beers is a series if it is a df you will need column name as well

beers_mean = beers.mean()
beers[:10].apply(lambda x: 'low' if (x-beers_mean)<0 else 'high'

it cant resultve the beers[:10] - beers.mean() into a new series that why you got an exception

if beers is a DF and you want to do this on a single column in the table then just picked it first

beer_col = beers[['col_name']]
beers_mean = beer_col .mean()
beer_col[:10].apply(lambda x: 'low' if (x-beers_mean)<0 else 'high'
Related