Reputation: 331
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.
Upvotes: 0
Views: 83
Reputation: 141
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.
Upvotes: 1
Reputation: 1182
A possible way is:
y0 = y[0:len(x_bin[0])]
and so on, but it is not very elegant.
instead of using y0 = ...
y1 = ...
you can make a list of slices:
slices = []
for n in len(y):
slices.append(y[n:len(x_bin[0])])
(this might be wrong, but the principle is there)
instead of haveing y0
y1
and so on, you will have slices[0]
, slices[1]
and so on
Upvotes: 0