Skip to main content
 首页 » 编程设计

python之基于列向量制作 Pandas 面具

2025年05月04日8grandyang

我有一个给定的数据框,我希望每一行都能够选择高于该行给定百分位数的值。

让我们考虑这个数据框:

df = pd.DataFrame({'A' : [5,6,3,4, 0,5,9], 'B' : [1,2,3, 5,7,0,1]}) 
 
   A  B 
0  5  1 
1  6  2 
2  3  3 
3  4  5 
4  0  7 
5  5  0 
6  9  1 

每行的第 20 个分位数的给定向量:

rowsQuantiles = df.quantile(0.2, axis=1) 
 
0    1.8 
1    2.8 
2    3.0 
3    4.2 
4    1.4 
5    1.0 
6    2.6 

我希望能够为每一行过滤掉低于该行分位数的值,以获得以下结果:

quantileMask = df > rowsQuantiles 
 
   A      B 
0  True   False 
1  True   False 
2  False  False 
3  False  True   
4  False  True   
5  True   False 
6  True   False 

编辑:

我真的很喜欢@andrew_reece 和@Andy Hayden 的两种方法,所以我决定看看哪一种是最快/实现最好的:

N=10000000 
df = pd.DataFrame({'A' : [random.random() for i in range(N)], 'B' : [random.random() for i in range(N)]}) 
rowsQuantiles = df.quantile(0.2, axis=1) 
 
t0=time.time() 
 
mask=(df.T>rowsQuantiles).T 
#mask=df.apply(lambda row: row > rowsQuantiles) 
 
print(str(time.time()-t0)) 

结果非常简单(经过多次重复测试):

  • 220ms for mask=(df.T>rowsQuantiles).T
  • 65ms for mask=df.apply(lambda row: row > rowsQuantiles)
  • 21ms for df.gt(rowsQuantiles,0),已接受的答案。

请您参考如下方法:

同样只使用 gt

df.gt(rowsQuantiles,0) 
Out[288]:  
       A      B 
0   True  False 
1   True  False 
2  False  False 
3  False   True 
4  False   True 
5   True  False 
6   True  False 

使用添加

df.add(-rowsQuantiles,0).gt(0) 
Out[284]:  
       A      B 
0   True  False 
1   True  False 
2  False  False 
3  False   True 
4  False   True 
5   True  False 
6   True  False