Axel.Schweiß
Axel.Schweiß

Reputation: 67

Count number of elements in a column greater than x but smaller than y

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

Answers (3)

jpp
jpp

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

Rudolf Morkovskyi
Rudolf Morkovskyi

Reputation: 869

a= df['xyz'] 
df[(a < 2/3) & (a > 1/3)].count()

Upvotes: 1

Frayal
Frayal

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

Related Questions