简体   繁体   中英

How to count the number of times a value is in a bin of a 2d histogram in python?

Is there a method I can use to count the number of times an individual value (say, 1) appears in each bin of a weighted 2d histogram? I have a weighted 2d histogram that is created using np.histogram2d(x, y, weight=weight, bins=45).

I know that I can use something like (counts, _, _) = np.histogram2d(x, y, bins=45) to view the total number of values in each bin, and then I can view the weighted counts by doing np.histogram2d(x, y, weight=weight, bins=45). However, with the weighted histogram, I want to see how many times the default value of '1' is appearing in each of the 45 bins. Is there a simple way to do this?

You could either use np.unique() (with return_counts flag set to True ) to count the number of occurrences for each individual value that appear on an array, or you could use a combination of np.count_nonzero() and equality comparison on the array, eg:

  • with np.unique() :
import numpy as np


np.random.seed(0)  # make sure the example is reproducible
arr = np.random.randint(0, 10, 1000)

values, counts = np.unique(arr, return_counts=True)
print(values)
# [0 1 2 3 4 5 6 7 8 9]
print(counts)
# [ 99  96  97 122  99 105  94  97  95  96]
  • with np.count_nonzero()
import numpy as np


np.random.seed(0)  # make sure the example is reproducible
arr = np.random.randint(0, 10, 1000)

print(np.count_nonzero(arr == 1))
# 96

You cannot retrieve the same information from the result of np.histogram() or np.histogram2d() , which are, by definition, aggregate results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM