3

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?

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.