我想獲得一個numpy的陣列是浮動型的bincount:NumPy的bincount()用浮漂
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
print np.bincount(w)
你怎麼能使用bincount()的浮點值,而不是詮釋?
我想獲得一個numpy的陣列是浮動型的bincount:NumPy的bincount()用浮漂
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
print np.bincount(w)
你怎麼能使用bincount()的浮點值,而不是詮釋?
你想要這樣的東西嗎?
>>> from collections import Counter
>>> w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> c = Counter(w)
Counter({0.10000000000000001: 2, 0.5: 1, 0.29999999999999999: 1, 0.20000000000000001: 1})
,或者更漂亮輸出:
Counter({0.1: 2, 0.5: 1, 0.3: 1, 0.2: 1})
然後,您可以進行排序,並得到你的價值觀:
>>> np.array([v for k,v in sorted(c.iteritems())])
array([2, 1, 1, 1])
的bincount
輸出就沒有意義浮筒:
>>> np.bincount([10,11])
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
,因爲沒有明確的浮動順序。
在使用bincount
之前,您需要使用numpy.unique
。否則,它會模糊你正在計數的內容。對於numpy數組,unique
應該比Counter快得多。
>>> w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
>>> uniqw, inverse = np.unique(w, return_inverse=True)
>>> uniqw
array([ 0.1, 0.2, 0.3, 0.5])
>>> np.bincount(inverse)
array([2, 1, 1, 1])
自1.9.0版本,你可以直接使用np.unique
:
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
values, counts = np.unique(w, return_counts=True)
,你會期望從這樣的「怪」操作的結果是什麼? – luke14free 2012-04-12 07:46:38
我想知道每個值的出現次數。所以結果是:[2,1,1,1]因爲0.1出現兩次而其他一次出現。 – user1220022 2012-04-12 07:47:56