pythonarraysnumpydimensionsmatrix-indexing

Accessing an individual element in a Numpy array of arbitrary dimensions


So. I am trying to access and modify the penultimate individual element of a series of Numpy arrays.

array_1D = np.array([10,11,12,13, 14])
array_2D = np.array([[20,30,40,50,60], [43,54,65,76,87], [11,22,33,44,55]])
array_3D = np.array([[[1,2,3,4,5], [11,21,31,41,51]], [[11,12,13,14,15], [51,52,53,54,5]]])
arrays = [array_1D, array_2D, array_3D]

I wanted to do this programmatically as opposed to manually, to learn a bit deeper.

What I have is:

for array in arrays:
    print(array)  # Before
    print('CHANGE TEN')
    array[..., -2] = 10
    print(array, end='\n--------\n\n')  # After

Which returns:

[10 11 12 13 14]
CHANGE TEN
[10 11 12 10 14]
--------

[[20 30 40 50 60]
 [43 54 65 76 87]
 [11 22 33 44 55]]
CHANGE TEN
[[20 30 40 10 60]
 [43 54 65 10 87]
 [11 22 33 10 55]]
--------

[[[ 1  2  3  4  5]
  [11 21 31 41 51]]

 [[11 12 13 14 15]
  [51 52 53 54  5]]]
CHANGE TEN
[[[ 1  2  3 10  5]
  [11 21 31 10 51]]

 [[11 12 13 10 15]
  [51 52 53 10  5]]]
--------

As you can see this syntax currently accesses the penultimate individual element of all elements along the major axis.

Is there a neat way to access the penultimate individual element of an array of arbitrary dimension? (In this case that would mean a single integer.)

Strange application I know. I'm interested in understanding the limitations germane to working with arrays of arbitrary dimension.

(I googled a bit and searched SO to no avail. Google Fu not strong apparently.)


Solution

  • Here you go:

    array_1D = np.array([10,11,12,13, 14])
    array_2D = np.array([[20,30,40,50,60], [43,54,65,76,87], [11,22,33,44,55]])
    array_3D = np.array([[[1,2,3,4,5], [11,21,31,41,51]], [[11,12,13,14,15], [51,52,53,54,5]]])
    arrays = [array_1D, array_2D, array_3D]
    
    for array in arrays:
        print(array)  # Before
        print('CHANGE TEN')
        array[tuple([-2] * array.ndim)] = 10
        print(array, end='\n--------\n\n')  # After
    
    print(array_1D[-2], array_2D[-2,-2], array_3D[-2,-2,-2])
    

    Output:

    10 10 10