使用特定于行的标准筛选numpy数组

2024-04-19 16:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个2d numpy数组,我想在每行的基础上过滤通过某个条件的元素。例如,我只需要第90个百分位以上的元素作为其特定行的。我想出了一个解决方案:

import numpy as np
a = np.random.random((6,5))
thresholds = np.percentile(a, 90, axis=1)
threshold_2d = np.vstack([thresholds]*a.shape[1]).T
mask = a > threshold_2d
final = np.where(mask, a, np.nan)

它是可行的,它是矢量化的,但感觉有点尴尬,尤其是我创建threshold_2d的部分。有没有更优雅的方式?我能用某种方式自动广播一个条件吗np.哪里不必创建匹配的2d蒙版?在


Tags: importnumpy元素thresholdasnp方式mask
1条回答
网友
1楼 · 发布于 2024-04-19 16:24:22

广播

In [36]: np.random.seed(1023)

In [37]: a = np.random.random((6,5))

In [38]: thresholds = np.percentile(a, 90, axis=1)

In [39]: threshold_2d = np.vstack([thresholds]*a.shape[1]).T

In [40]: a>threshold_2d
Out[40]: 
array([[ True, False, False, False, False],
       [False, False,  True, False, False],
       [False,  True, False, False, False],
       [False, False, False,  True, False],
       [False, False, False, False,  True],
       [False,  True, False, False, False]], dtype=bool)

In [41]: a>thresholds[:,np.newaxis]
Out[41]: 
array([[ True, False, False, False, False],
       [False, False,  True, False, False],
       [False,  True, False, False, False],
       [False, False, False,  True, False],
       [False, False, False, False,  True],
       [False,  True, False, False, False]], dtype=bool)

In [42]: 

^{}创建长度为1的轴,生成的数组视图具有维度(6,1),可以使用a数组进行广播。在

相关问题 更多 >