python + dataframe + counts elements in a single line based on boolean

advertisements

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!


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