2

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!

1
  • Can you try to add axis=1 param in the apply func? Commented Sep 18, 2021 at 14:02

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.