1

for example

I have a point list

a = np.array([[0,0,0],
              [1,1,1],
              [2,2,2],
              [3,3,3],
              [4,4,4],
              [5,5,5],
              [6,6,6],
              [7,7,7],
              [8,8,8],
              [9,9,9]])

and I have another array represents the number of elements

b = np.array([2,0,3,5])

how can I split array a according the number of elements of array b so that I can get the output

[[[0,0,0],[1,1,1]],
 [],
 [[2,2,2],[3,3,3],[4,4,4]],
 [[5,5,5],[6,6,6],[7,7,7],[8,8,8],[9,9,9]]]
5
  • shouldn't the [4,4,4] be in the third group? Commented May 10, 2022 at 9:14
  • no, [4,4,4] should be in the third group, because the group 3 contains 3 members and group 4 contains 5 members. Commented May 10, 2022 at 9:19
  • That's what I said, so the current provided output is incorrect ;) Commented May 10, 2022 at 9:20
  • the the provided answer should work for you Commented May 10, 2022 at 9:21
  • did it work as you want? Commented May 10, 2022 at 14:45

1 Answer 1

1

You can use numpy.split using cumsum on b to get the split points:

out = np.split(a, b.cumsum()[:-1])

output:

[array([[0, 0, 0],
        [1, 1, 1]]),
 array([], shape=(0, 3), dtype=int64),
 array([[2, 2, 2],
        [3, 3, 3],
        [4, 4, 4]]),
 array([[5, 5, 5],
        [6, 6, 6],
        [7, 7, 7],
        [8, 8, 8],
        [9, 9, 9]])]

If you want lists:

out = [x.tolist() for x in np.split(a, b.cumsum()[:-1])]

output:

[[[0, 0, 0], [1, 1, 1]],
 [],
 [[2, 2, 2], [3, 3, 3], [4, 4, 4]],
 [[5, 5, 5], [6, 6, 6], [7, 7, 7], [8, 8, 8], [9, 9, 9]]]

intermediate:

b.cumsum()[:-1]
# array([2, 2, 5])
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.