numpy.bincount正確理解


  今天看了個方法,numpy.bincount首先官網文檔:

numpy.bincount

numpy. bincount (xweights=Noneminlength=0)

Count number of occurrences of each value in array of non-negative ints.

The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position iout[n] += weight[i] instead of out[n] += 1.

Parameters:
x  array_like, 1 dimension, nonnegative ints

Input array.

weights  array_like, optional

Weights, array of the same shape as x.

minlength  int, optional

A minimum number of bins for the output array.

New in version 1.6.0.

Returns:
out  ndarray of ints

The result of binning the input array. The length of out is equal to np.amax(x)+1.

Raises:
ValueError

If the input is not 1-dimensional, or contains elements with negative values, or if minlength is negative.

TypeError

If the type of the input is float or complex.

 

大意思是:  一臉懵逼好吧,統計bin在x出現的次數,what is bin?長度是x中最大值的+1,也看了一些博客,有些是這樣寫的:

 

仔細看了看這個例子,還是沒看懂,難道是我智商有問題?索引值0->7  哪里看出來的?官網文檔也沒說呀

索引0出現1次?x的索引0上數字是0,缺失出現了1次,1出現3次對的,后面索引2也是1應該也是3呀 什么鬼?怎么結果是1???

最終,我發現了到底是怎么統計的了,這個函數要求x里面的數字是非負正數是有道理的,

函數返回的是固定的array[0, 1, 2, 3, ... , N]這個數據對應數字在該數組x中出現的次數。

那么我們來驗證一下經典的例子:

x = np.array([0, 1, 1, 3, 2, 1, 7])

第一個是看0在x中出現幾次,1次;

1出現幾次,3次;

2出現幾次,1次;

3出現幾次,1次;

4出現幾次,0次;

5出現幾次,0次;

6出現幾次,0次;

7出現幾次,1次

結果:

np.bincount(x)

array([0, 1, 1, 0, 1, 0, 1, 1])

完美,再試一個?

也是對的,為啥要長度的最大值加一呢,顯然是這里從0開始計算出現次數的,所以最后一個是最大值,數組長度要加1了。

 另外一個驗證方式,z的數字求和肯定和np.bincount(z).dot(np.arange(max(z)+1))相等

至於其它參數就不介紹了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM