Skip to content
Advertisement

Slice array using other array

I have two arrays of the same length that contain elements from 0 to 1. For example:

x = np.linspace(0,1,100)
y = np.random.permutation(x)

I grouped the elements of x in bins of width 0.1:

bins = np.arange(0,1,0.1)
x_bin = []
for i in range(1,10):
    x_bin.append(x[np.digitize(x,bins)==i])

Now I would like to slice y in groups which have the same lengths of the arrays in x_bin.

How can I do that?

A possible way is:

y0 = y[0:len(x_bin[0])]

and so on, but it is not very elegant.

Advertisement

Answer

This may be what you want to use as a more elegant solution than using loops:

l = [len(x) for x in x_bin]  # get bin lengths
split_indices = np.cumsum(l)  # sum up lengths for correct split indices
y_split = np.split(y, split_indices)

I got the array lengths via list comprehension and then splitted the np array using the gathered indices. This can be shortened to a single python instruction, but it is much easier to read this way.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement