如何计算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] ]]])
答案 0 :(得分: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])
从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]]