. Advertisement .
..3..
. Advertisement .
..4..
Hi everyone. I’m learning about pandas DataFrame and I’m in trouble with ”the truth value of a series is ambiguous. use a.empty, a.bool(), a.item(), a.any() or a.all().” error. Here is the detail of program which I run:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'points': [18, 22, 19, 14, 14, 11, 20, 28],
'assists': [5, 7, 7, 9, 12, 9, 9, 4],
'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})
#view DataFrame
print(df)
team points assists rebounds
0 A 18 5 11
1 A 22 7 8
2 A 19 7 10
3 A 14 9 6
4 B 14 12 6
5 B 11 9 5
6 B 20 9 9
7 B 28 4 12
I receive this error when I try to filter for rows where the team is equal “A” and the points are less than 20:
#attempt to filter DataFrame
df[(df['team'] == 'A') and (df['points'] < 20)]
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(),
a.any() or a.all().
And when we I try to filter for rows where the team is equal to “A” or the points is less than 20, I get following error:
#attempt to filter DataFrame
df[(df['team'] == 'A') or (df['points'] < 20)]
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(),
a.any() or a.all().
I have read a lot of documents but I haven’t found the desired answer. Can you help me with this problem? Please write your suggestions below. Thanks!
The cause:
This error happens because instead of using the & and | operators, you try to filter a pandas DataFrame with the words and and or.
Solution:
To solve this error, you have to use the & and | instead of the words and and or.
Below are the codes I suggest: