![](/img/trans.png)
[英]Counting the number of non-NaN elements in a numpy ndarray in Python
[英]Count number of elements in numpy ndarray
如何計算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] ]]])
這樣的事情怎么樣?
首先計算數組中的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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.