Python + 数据帧 + 基于布尔值对单行中的项目进行计数



我有一种感觉,有一个简单的方法可以做到这一点......我有一个数据帧,如下所示:

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

我正在尝试弄清楚如何:

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

即,对于索引 = 1,返回 <10 的值的数量。(所以应该返回 1)

谢谢!

您可以使用DF.query()进行选择,如下所示:(假设您要查询可能重复的索引轴)

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

它是.loc等效语法:

df1.loc[df1.index==1].lt(10).sum(1)
Out[58]:
Index
1    1
dtype: int64
您可以使用

.loc,您当前的索引尝试有点丑陋的语法错误。

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

最新更新