2

如何计算 ndarray 中每个数据点的元素数?

我想要做的是对我的 ndarray 中至少存在 N 次的所有值运行 OneHotEncoder。

我还想用另一个没有出现在数组中的元素替换所有出现少于 N 次的值(我们称之为 new_value)。

所以例如我有:

import numpy as np

a = np.array([[[2], [2,3], [3,34]],
              [[3], [4,5], [3,34]],
              [[3], [2,3], [3,4] ]]])

阈值 N=2 我想要类似的东西:

b = [OneHotEncoder(a[:,[i]])[0] if count(a[:,[i]])>2 
else OneHotEncoder(new_value) for i in range(a.shape(1)]

所以只是为了理解我想要的替换,不考虑 onehotencoder 并使用 new_value=10 我的数组应该如下所示:

a = np.array([[[10], [2,3], [3,34]],
                [[3], [10], [3,34]],
                [[3], [2,3], [10] ]]])
4

1 回答 1

6

这样的事情怎么样?

首先计算数组中的 unqiue 元素个数:

>>> a=np.random.randint(0,5,(3,3))
>>> a
array([[0, 1, 4],
       [0, 2, 4],
       [2, 4, 0]])
>>> ua,uind=np.unique(a,return_inverse=True)
>>> count=np.bincount(uind)
>>> ua
array([0, 1, 2, 4]) 
>>> count
array([3, 1, 2, 3]) 

uacount数组中可以看出,0 出现 3 次,1 出现 1 次,依此类推。

import numpy as np

def mask_fewest(arr,thresh,replace):
    ua,uind=np.unique(arr,return_inverse=True)
    count=np.bincount(uind)
    #Here ua has all of the unique elements, count will have the number of times 
    #each appears.


    #@Jamie's suggestion to make the rep_mask faster.
    rep_mask = np.in1d(uind, np.where(count < thresh))
    #Find which elements do not appear at least `thresh` times and create a mask

    arr.flat[rep_mask]=replace 
    #Replace elements based on above mask.

    return arr


>>> a=np.random.randint(2,8,(4,4))
[[6 7 7 3]
 [7 5 4 3]
 [3 5 2 3]
 [3 3 7 7]]


>>> mask_fewest(a,5,50)
[[10  7  7  3]
 [ 7  5 10  3]
 [ 3  5 10  3]
 [ 3  3  7  7]]

对于上面的示例:如果您打算使用 2D 数组或 3D 数组,请告诉我。

>>> a
[[[2] [2, 3] [3, 34]]
 [[3] [4, 5] [3, 34]]
 [[3] [2, 3] [3, 4]]]


>>> mask_fewest(a,2,10)
[[10 [2, 3] [3, 34]]
 [[3] 10 [3, 34]]
 [[3] [2, 3] 10]]
于 2013-07-24T23:51:11.670 回答