5

I'm sorry to ask this apparently simple question, but I am a python beginner and couln't find an answer anywhere. I want to run a simple if statement, but python returns just:

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

No matter which of the given alternatives I apply - it just doesn't work. Do you have any ideas?

    import pandas as pd

    df = pd.DataFrame({'a': [None] * 4, 'b': [2, 3, 10, 3]})

    df["c"] =0    
    if df.b == 2:
        df.c =1

5 Answers 5

3

In if statement you're trying to compare an array with scalar. You can use something like

if df.b[0] == 2:
    df.c =1

or

if 2 in df.b:
    df.c =1

if you want to check for a specific element in the array.

Sign up to request clarification or add additional context in comments.

Comments

2

You can't compare a scalar with an array like that using if it becomes ambiguous as what if one of the values matches or all but one you want to do something like:

In [3]:

df['c'] = np.where(df['b'] == 2, 1, np.NaN)
df
Out[3]:
      a   b   c
0  None   2   1
1  None   3 NaN
2  None  10 NaN
3  None   3 NaN

using np.where looks at the whole array for that condition and if True returns 1, otherwise NaN

You can perform comparisons using syntax like:

In [4]:

df['b'] == 2
Out[4]:
0     True
1    False
2    False
3    False
Name: b, dtype: bool

but not using if unless you are comparing a single value:

In [8]:

for index, row in df.iterrows():
    if row['b'] == 2:
        print('equals 2')
    else:
        print('some other value')
equals 2
some other value
some other value
some other value

Comments

1

You set df.b to be a list containing four numbers. It can never equal a single number.

And Pandas cannot handle comparing a list to anything using == because it's not clear what answer you want, so it's prompting you to explain.

http://pandas.pydata.org/pandas-docs/stable/gotchas.html

I don't think you are trying to do that at all, but it's not clear what you are expecting to happen.

Comments

0

you are trying to check if df.b, a List, is equal to an int.

Try this:

if 2 in df.b:
   df.c=1

Comments

0

Well, first off. you're trying to use a conditional on an entire dictionary!

You're basically saying "if this dicitonary == 2", which simply is an ambiguous statement because that dictionary (df.b) is a set of values, which doesn't necessarily evaluate to "true"...

df.b is

0     2
1     3
2    10
3     3

Honestly, based on your question, I'm not entirely sure what you're trying to evaluate! You should try printing df before you evaluate in the sub-ccomposition of df.b.

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.