Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

pandas - If condition for comparison between two dataframes in Python

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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...