keynesiancross
keynesiancross

Reputation: 3529

python + dataframe + count items in a single row based on boolean

I have a feeling there is a simple way to do this... I have a dataframe as follows:

df1 = 
    Index  A     B     C
    0      5     7     11
    1      10    7     11

I am trying to figure out how to:

df1['Index'==1][<10].count()

Ie, for index = 1, return the number of values that are <10. (so should return 1)

Thanks!

Upvotes: 2

Views: 87

Answers (2)

Nickil Maveli
Nickil Maveli

Reputation: 29719

You can do the selection using DF.query() as follows: (assuming you want to query the index axis which may be duplicated)

df1.query("Index == 1").lt(10).sum(1)      # assuming the index name as "Index"
Out[56]:
Index
1    1
dtype: int64

It's .loc equivalent syntax:

df1.loc[df1.index==1].lt(10).sum(1)
Out[58]:
Index
1    1
dtype: int64

Upvotes: 2

miradulo
miradulo

Reputation: 29740

You can use .loc for this, your current attempt at indexing is a bit of an ugly syntax error.

In[32]: df.loc[1].lt(10).sum()
Out[32]: 1

Upvotes: 1

Related Questions