3

Am new to python programming. Can anyone pls check the below syntax for if condition-

if df1[A]<= df2[B]):
       print("")
else:
       print("")

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

3
  • 2
    There is a bracket you close, but never opened? Commented Feb 6, 2017 at 15:42
  • It seems you need any - (df1[A]<= df2[B]).any() Commented Feb 6, 2017 at 15:43
  • Apologies for being syntactically wrong. Yes there is a parenthesis '(' Commented Feb 6, 2017 at 18:08

1 Answer 1

9

You compare arrays, no scalar, so output of camparing is another array. So need any or all. Also need length of both Series is same:

df1 = pd.DataFrame({'A':[1,2,3]})
print (df1)
   A
0  1
1  2
2  3

df2 = pd.DataFrame({'B':[1,2,0]})
print (df2)
   B
0  1
1  2
2  0

print (df1['A']<= df2['B'])
0     True
1     True
2    False
dtype: bool

#check if at least one True
print ((df1['A']<= df2['B']).any())
True

#check if all values are True
print ((df1['A']<= df2['B']).all())
False
if (df1['A']<= df2['B']).any():
       print("at least one value True")
else:
       print("no False values")
at least one value True

if (df1['A']<= df2['B']).all():
       print("all values True")
else:
       print("not all values True")

not all values True

df1 = pd.DataFrame({'A':[1,2,3]})
print (df1)
   A
0  1
1  2
2  3

df2 = pd.DataFrame({'B':[1,2,3]})
print (df2)
   B
0  1
1  2
2  3

print (df1['A']<= df2['B'])
0    True
1    True
2    True
dtype: bool

#check if at least one True
print ((df1['A']<= df2['B']).any())
True

#check if all values are True
print ((df1['A']<= df2['B']).all())
True
if (df1['A']<= df2['B']).any():
       print("at least one value True")
else:
       print("no False values")

at least one value True

if (df1['A']<= df2['B']).all():
       print("all values True")
else:
       print("not all values True")

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

2 Comments

no more true. I am using v.19.2 and df1 = pandas.DataFrame({'A':[1,2,3]}); df2 = pandas.DataFrame({'B':[2,2,3]}); df1 > df2; gives an error "ValueError: Can only compare identically-labeled DataFrame objects"
@lehalle - You need compare columns print (df1['A'] > df2['B'])

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.