Can numpy array be accessed using an indexing object?

Question:

Please assume

a = np.zeros((4, 5, 6, 7, 8))

I can access or slice the array like so

element = a[2, 3, 4, 5, 6]
sub_array = a[1:2, 1:3, 1:4, 1:4, 1:6]

I would like to dynamically, separately create the 2, 3, 4, 5, 6 or 1:2, 1:3, 1:4, 1:4, 1:6 part, then access a with it.

Something such as

b = 1:2, 1:3, 1:4, 1:4, 1:6
a[b]

Is that supported in numpy?

Asked By: Gulzar

||

Answers:

Would something like this work? I might be confused on what you want as an end output:

a = np.array((4, 5, 6, 7, 8))
elementSlice = [2,3,4,5,6]
subSlice = ["1:2", "1:3", "1:4", "1:4", "1:6"]

def elem_help(val, arr):
    try:
        return arr[val]
    except:
        pass
    
def sub_help(val, arr):
    try:
        val1 =  int(val.split(":")[0])
        val2 =  int(val.split(":")[1])
        return list(arr[val1:val2])
    except:
        pass

element = list(filter(None, [elem_help(x, a) for x in elementSlice]))
sub_array = list(filter(None, [sub_help(x, a) for x in subSlice]))

element output:

[6, 7, 8]

sub_array output:

[[5], [5, 6], [5, 6, 7], [5, 6, 7], [5, 6, 7, 8]]
Answered By: Michael S.
a = np.zeros((4, 5, 6, 7, 8))
b = slice(1,2), slice(1, 3), slice(1,4), slice(1, 4), slice(1,6)
a[b]

gives the following:

array([[[[[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]],

     [[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]],

     [[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]]],


    [[[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]],

     [[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]],

     [[0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.],
      [0., 0., 0., 0., 0.]]]]])

and

a = np.zeros((4, 5, 6, 7, 8))
c = 1, 2, 3, 4, 5
a[c]

gives:

0.0

Is this what you’re looking for?

Answered By: Alex Meredith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.