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
448 views
in Technique[技术] by (71.8m points)

Error: The truth value of a Series is ambiguous - Python pandas

I know this question has been asked before, however, when I am trying to do an if statement and I am getting an error. I looked at this link , but did not help much in my case. My dfs is a list of DataFrames.

I am trying the following,

for i in dfs:
    if (i['var1'] < 3.000):
       print(i)

Gives the following error:

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

AND I tried the following and getting the same error.

for i,j in enumerate(dfs):
    if (j['var1'] < 3.000):
       print(i)

My var1 data type is float32. I am not using any other logical operators and & or |. In the above link it seemed to be because of using logical operators. Why do I get ValueError?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here is a small demo, which shows why this is happenning:

In [131]: df = pd.DataFrame(np.random.randint(0,20,(5,2)), columns=list('AB'))

In [132]: df
Out[132]:
    A   B
0   3  11
1   0  16
2  16   1
3   2  11
4  18  15

In [133]: res = df['A'] > 10

In [134]: res
Out[134]:
0    False
1    False
2     True
3    False
4     True
Name: A, dtype: bool

when we try to check whether such Series is True - Pandas doesn't know what to do:

In [135]: if res:
     ...:     print(df)
     ...:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
...
skipped
...
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Workarounds:

we can decide how to treat Series of boolean values - for example if should return True if all values are True:

In [136]: res.all()
Out[136]: False

or when at least one value is True:

In [137]: res.any()
Out[137]: True

In [138]: if res.any():
     ...:     print(df)
     ...:
    A   B
0   3  11
1   0  16
2  16   1
3   2  11
4  18  15

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

...