Reputation: 67
I am trying to count the number of elements in column 'xyz'
which are smaller than x
but larger than y
.
a= df['xyz']
df[1/3 < a < 2/3].count()
However, this gives me:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Upvotes: 1
Views: 2225
Reputation: 164673
Subsetting your dataframe is not necessary. Just sum a Boolean series:
res = df['xyz'].between(1/3, 2/3, inclusive=False).sum()
Chained comparisons such as x < a < y
work with regular Python scalars, not with Pandas objects, which require vectorised operations.
Upvotes: 2
Reputation: 2161
this will give you the df where it's true:
mask = (df['xyz'] > min) & (df['xyz'] <= max)
df = df[mask]
then:
len(df) or df.count() or df.shape[0]
or just:
sum(mask)
Upvotes: 1