如何计算 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] ]]])
最佳答案
这样的事情怎么样?
首先统计数组中不存在元素的个数:
>>> 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])
从 ua
和 count
数组可以看出,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]]
关于python - 计算 numpy ndarray 中的元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17846613/