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?
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:
low and hight edges of each bin.zenith_angles array.rates values at the indexes obtained at previous step.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With