One error you may encounter in Python is the following:
TypeError:Cannot perform 'rand_' with a dtyped [int64] array and scalar of type [bool]
This error usually occurs when you attempt to filter a pandas DataFrame using multiple conditions but fail to use parenthesis around each individual condition.
The following example shows how to fix this error in practice.
How to Reproduce the Error
Suppose we have the following pandas DataFrame:
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
Now suppose we attempt to filter the DataFrame to only show rows where the team column is equal to ‘A’ and the points column is greater than 15:
#attempt to filter DataFrame
df.loc[df.team == 'A' & df.points > 15]
TypeError:Cannot perform 'rand_' with a dtyped [int64] array and scalar of type [bool]
We receive an error because we didn’t place parenthesis around each individual condition.
How to Fix the Error
To fix this error, we just need to make sure we place parenthesis around each individual condition when performing the filter:
#filter DataFrame
df.loc[(df.team == 'A') & (df.points > 15)]
team points assists rebounds
0 A 18 5 11
1 A 22 7 8
2 A 19 7 10
Notice that we’re able to successfully filter the DataFrame to only show the rows where team is equal to ‘A’ and where points is greater than 15.
Note that we also need to place parenthesis around each individual condition if we’re using an or “|” operator instead:
#filter rows where team is equal to 'A' or points is greater than 15
df.loc[(df.team == 'A') | (df.points > 15)]
team points assists rebounds
0 A 18 5 11
1 A 22 7 8
2 A 19 7 10
3 A 14 9 6
6 B 20 9 9
7 B 28 4 12
Notice that we avoid any errors once again.
Additional Resources
The following tutorials explain how to fix other common errors in pandas:
How to Fix: module ‘pandas’ has no attribute ‘dataframe’
How to Fix: TypeError: no numeric data to plot
How to Fix KeyError in Pandas