Skip to main content

bincount

Function bincount 

Source
pub fn bincount<T, W>(
    x: &Array<T>,
    weights: Option<&Array<W>>,
    minlength: Option<usize>,
) -> Result<Array<W>>
Expand description

Count number of occurrences of each value in array of non-negative integers

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.

§Parameters

  • x - Input array of non-negative integers
  • weights - Optional weights array of the same shape as x
  • minlength - Minimum number of bins for output array

§Returns

Array of counts. The length of the output is equal to max(x) + 1 if x is non-empty, and at least minlength.

§Examples

use numrs2::prelude::*;
use numrs2::array_ops::sorting::bincount;

// Basic bincount
let x = Array::from_vec(vec![0, 1, 1, 3, 2, 1, 7]);
let counts: Array<i32> = bincount(&x, None, None).expect("operation should succeed");
// counts = [1, 3, 1, 1, 0, 0, 0, 1] (8 elements, up to max value 7)
assert_eq!(counts.shape(), vec![8]);
assert_eq!(counts.get(&[1]).expect("operation should succeed"), 3); // value 1 appears 3 times

// With weights
let weights = Array::from_vec(vec![0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 2.0]);
let weighted_counts: Array<f64> = bincount(&x, Some(&weights), None).expect("operation should succeed");
assert_eq!(weighted_counts.get(&[1]).expect("operation should succeed"), 1.5); // sum of weights where x=1