Skip to main content
 首页 » 编程设计

python之获取 'pandas' 中对另一个变量为 True 的每个变量的比例

2025年05月04日9kevingrace

我在 pandas 中有一个数据框,其中包括一个列“A”和一个 bool 值列“B”,我想找到至少某个数字的“A”的值, n, 行的“B”为真。

我能想到的最接近的是

df.query('B == True')['A'].value_counts() 

然后查看数字,看看哪些大于 n。

是否有更 pythonic(或更多 ailuropodian)的方法来执行此操作(甚至可能是一种方法,它们只返回计数大于 n 的那些,或者是 True 的比例)?

请您参考如下方法:

这听起来类似于过滤器:

In [11]: df = pd.DataFrame([[1, True], [1, True], [2, False], [2, True]], columns=['A', 'B']) 
 
In [12]: g = df.groupby('A') 
 
In [13]: g.filter(lambda x: x['B'].sum() > 1) 
Out[13]:  
   A     B 
0  1  True 
1  1  True 

要仅找到 A 为 True 的值,您可以使用 sum agg 方法:

In [21]: res = g.B.sum() > 1 
 
In [22]: res[res] 
Out[22]:  
A 
1    True 
Name: B, dtype: bool 
 
In [23]: res[res].index 
Out[23]: Int64Index([1], dtype='int64')