0

I take an array with several rows:

import numpy as np
a = np.arange(1, 7)
a = a.reshape(2, -1)
print (a)
[[1 2 3]
 [4 5 6]]

I need to access first element of the next row after the last element of the current row:

print (a[0][2:4])
[3]

I expect here:

[3 4]

I also need to access first element of the first row after the last element of the last row:

print (a[1][2:4])
[6]

I expect here:

[6 1]

Could you recommend me the easiest way to achieve this?

1 Answers1

0

You're attempting to access indices that aren't there. Your a[0] includes indices [0, 1, 2], attempting to access index 3 is thus out of range. Your options are limited to keeping the array in it's original flattened shape to get the correct slices. Even in this situation you will need an additional function to cycle past last index. Either case you have to flatten your array:

def getslice(arr, row, start, end):
    if end + arr.shape[1] * row > arr.flatten().size:
        return np.concatenate((arr.flatten()[start + arr.shape[1] * row:],
                               arr.flatten()[:(end + arr.shape[1] * row) % arr.flatten().size]))
    else:
        return arr.flatten()[start + arr.shape[1] * row:end + arr.shape[1] * row]

Outputs:

getslice(a, 1, 2, 4) #a[1][2:4]
array([6, 1])
getslice(a, 0, 2, 5) #a[0][2:5]
array([3, 4, 5])
zck
  • 311
  • 1
  • 3