Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Histogram one array based on another array

I have two numpy arrays:

rates = [1.1, 0.8...]
zenith_anlges = [45, 20, ....]

both rates and zen_angles have the same length.

I also have some pre-defined zenith_angle bins,

zen_bins = [0, 10, 20,...]

What I need to do is bin the rates according to its corresponding zenith angle bins.

An ugly way to do it is

nbin = len(zen_bins)-1 
norm_binned_zen = [[0]]*nbin 
for i in range(nbin):
    norm_binned_zen[i] = [0]
for i in range(len(rates)):
    ind = np.searchsorted(zen_bins,zen_angles[i]) #The corresponding bin number
    norm_binned_zen[ind-1].append(rates[i])

This is not very pythonic and is time consuming for large arrays. I believe there must be some more elegant way to do it?

like image 292
Atreyee Avatar asked Aug 10 '26 00:08

Atreyee


1 Answers

The starting data (here randomly generated):

import numpy as np

rates = np.random.random(100)
zenith_angles = np.random.random(100)*90.0
zen_bins = np.linspace(0, 90, 10)

Since you are using numpy, you can use a one line solution:

norm_binned_zen = [rates[np.where((zenith_angles > low) & (zenith_angles <= high))] for low, high in zip(zen_bins[:-1], zen_bins[1:])]

Breaking this line into steps:

  • The list comprehension loops over pairs, the low and hight edges of each bin.
  • numpy.where is used to find the indexes of the angles inside the given bin in the zenith_angles array.
  • numpy indexing is used to select the rates values at the indexes obtained at previous step.
like image 79
Valentino Avatar answered Aug 11 '26 14:08

Valentino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!