我试图得到一个bin类型的浮动类型的numpy数组:
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
print np.bincount(w)
Run Code Online (Sandbox Code Playgroud)
你如何使用bincount()浮点值而不是int?
Bi *_*ico 11
您需要在使用numpy.unique前使用bincount.否则,你的数量是多么模糊.uniquenumpy数组应该比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])
Run Code Online (Sandbox Code Playgroud)
从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)
Run Code Online (Sandbox Code Playgroud)
你想要这样的东西吗?
>>> 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})
Run Code Online (Sandbox Code Playgroud)
或者,更好的输出:
Counter({0.1: 2, 0.5: 1, 0.3: 1, 0.2: 1})
Run Code Online (Sandbox Code Playgroud)
然后,您可以对其进行排序并获取您的值:
>>> np.array([v for k,v in sorted(c.iteritems())])
array([2, 1, 1, 1])
Run Code Online (Sandbox Code Playgroud)
bincount浮点数的输出没有意义:
>>> np.bincount([10,11])
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
Run Code Online (Sandbox Code Playgroud)
因为没有定义的浮点序列.
| 归档时间: |
|
| 查看次数: |
7880 次 |
| 最近记录: |