首页 > 解决方案 > 用于二维数组中非唯一元素的 numpy 过滤器

问题描述

import numpy as np

data = np.array(
    [
        ['a' 'a'],
        ['a' 'b'],
        ['d' 'c'],
        ['a' 'b'],
        ['d' 'c'],
        ['a' 'a'],
        ['b' 'a'],
        ['c' nan]
    ]
)

我如何过滤最频繁的子数组?预期结果:[['a' 'a'], ['d' 'c']]

标签: stringnumpyfilter2dunique

解决方案


我不太明白这个问题,但我认为np.unqiue可能有用。

data = np.array(
     [
         ['a', 'a'],
         ['a', 'b'],
         ['d', 'c'],
         ['a', 'b'],
         ['d', 'c'],
         ['a', 'a'],
         ['b', 'a'],
         ['c', np.nan]
     ]
 )

unique, idx, counts = np.unique(data[:,0], return_counts=True, return_index=True)
threshold = 1
data[idx[counts > threshold]]

输出:

array([['a', 'a'],
       ['d', 'c']], dtype='<U32')

推荐阅读