0

Say that I have an array of arrays

array = np.random.randint(0, 6, (4, 6))
array
array([[3, 5, 2, 5, 1, 3],
       [5, 3, 0, 1, 4, 3],
       [2, 1, 0, 2, 2, 4],
       [2, 1, 0, 4, 2, 2]])

And I also have arrays for desired start and end indices for slicing out this array for each row

starts = np.random.randint(0, 3, (4,))
ends = starts + 3
ends
array([6, 3, 4, 3])

How do I slice out the array of arrays using these indices?

For the example, the desired result will be

array([[5, 1, 3],
       [5, 3, 0],
       [1, 0, 2],
       [2, 1, 0]])

something like array[starts:ends] does not work

4
  • 1
    Either iterate row by row, or index once with [5,6,7, 3,4,5, 4,5,6, 3,4,5] Commented Jul 24, 2022 at 15:51
  • 1
    I think you made a mistake in the example: it is either array([6, 3, 4, 3]) or array([5, 2, 3, 2]), but the former is impossible with np.random.randint(0, 3, (4,)) and the later impossible with ends = starts + 3. So I expect the desired result not to be possible with the provided information: the first line should be 2, 5, 1. Commented Jul 24, 2022 at 15:59
  • @JérômeRichard sorry, I think it was an issue with double clicking a jupyter cell and not tracking the changes, I updated the post to reflect your statement. Commented Jul 24, 2022 at 16:06
  • It is still possible due to the second part of the previous comment. The last list is the one that matters the most ;) . Commented Jul 24, 2022 at 16:07

1 Answer 1

0

I am not sure but if this may help you:

a = []
i = 0
for s, e in zip(starts, ends):
    a.append(array[i][s:e])
    i += 1

Or use enumerate()

a = []
for i,(s, e) in enumerate(zip(starts, ends)):
    a.append(array[i][s:e])

then convert the list into an array to get the desired output

print(np.array(a))

It looks like this:

array([[2, 4, 2],
       [4, 3, 0],
       [2, 2, 0],
       [4, 0, 4]])
Sign up to request clarification or add additional context in comments.

5 Comments

it's better to use enumerate than to do += on a counting variable in a for loop
actually they have the same number of rows that's why I didn't use enumerate
what do you mean? I'm saying you should do for i, (s, e) in enumerate(zip(starts, ends)): and then get rid of i=0 and i+=1
yeah, that's a good option. I was thinking differently
Comprehension lists should be faster: a = [array[i][s:e] for i,(s, e) in enumerate(zip(starts, ends))]. np.fromiter without the list may be also even faster.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.