python - 过滤 numpy 数组以仅保留给定值的一行

标签 python arrays numpy

我有一个很大的 n x 2 numpy 数组,其格式为 (x, y) 坐标。我想过滤这个数组以便:

  1. 识别具有重复 x 值的坐标对。
  2. 仅保留那些具有最高 y 值的副本的坐标对。

例如,在下面的数组中:

arr = [[1, 4]
       [1, 8]
       [2, 3]
       [4, 6]
       [4, 2]
       [5, 1]
       [5, 2]
       [5, 6]]

我希望结果是:

arr = [[1, 8]
       [2, 3]
       [4, 6]
       [5, 6]]

我探索过 np.unique 和 np.where,但无法弄清楚如何利用它们来解决这个问题。非常感谢!

最佳答案

这是一种基于 np.maximum.reduceat 的方法 -

def grouby_maxY(a):
    b = a[a[:,0].argsort()] # if first col is already sorted, skip this
    grp_idx = np.flatnonzero(np.r_[True,(b[:-1,0] != b[1:,0])])
    grp_maxY = np.maximum.reduceat(b[:,1], grp_idx)
    return np.c_[b[grp_idx,0], grp_maxY]

或者,如果你想带上np.unique,我们可以用它来找到grp_idxnp.unique(b[:,0], return_index=1)[1].

sample 运行-

In [453]: np.random.seed(0)

In [454]: arr = np.random.randint(0,5,(10,2))

In [455]: arr
Out[455]: 
array([[4, 0],
       [3, 3],
       [3, 1],
       [3, 2],
       [4, 0],
       [0, 4],
       [2, 1],
       [0, 1],
       [1, 0],
       [1, 4]])

In [456]: grouby_maxY(arr)
Out[456]: 
array([[0, 4],
       [1, 4],
       [2, 1],
       [3, 3],
       [4, 0]])

关于python - 过滤 numpy 数组以仅保留给定值的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49908817/

相关文章:

python - 如何处理查询参数编码?

Python 3 替代 ftputil?

python - 为什么 numpy.ndarray.T 比 numpy.transpose(numpy.ndarray) 快得多?

python - 在 pyinstaller 可执行程序中找不到 Streamlit 发行版

python - 公开类的内部方法并使用它们

mysql - 将包含数组的 SQL 字段拆分为新表/行

php - 内爆时复制 PHP 数组中的第一个值

javascript - 如何使用express-validator对嵌套对象实现验证

Python 的 "StandardScaler"和 "LabelEncoder"以及 "fit"和 "fit_transform"不适用于同时包含 float 和字符串的 CSV

python - 使用两个数据框进行 Pandas 矢量化