0

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.

2
  • 1
    if all arrays are of equal length, y.reshape(x_bin[0].shape[0], -1) Commented Jul 8, 2021 at 11:15
  • Unfortunately, they are not Commented Jul 8, 2021 at 11:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

np.split hides another iteration. So your solution has two python level loops (plus a compiled one in the cumsum.
0

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

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.