I need to write a function that returns a single row or a column from a 2D array. The input to the function tells what to return.
# 3x3 array with values 1 to 9
a = np.arange(1, 10).reshape(3,3)
rowCount, colCount = a.shape
# return last row [7, 8, 9]
a[rowCount - 1, :]
# return first row [1, 2, 3]
a[0, :]
# return last column [3, 6, 9]
a[:, lastCol]
# return first column [1, 4, 7]
a[:, 0]
How can I do this in a function, such that the function receives the row or column to return?
Something like,
def getSlice(slice):
return a[slice]
Where the slice object is created using the built-in slice function.
However, I cannot figure out how to create a slice object for a 2D array, due to the fact that slice
function does not accept the colon operator like slice(0, :)
.
Also, is there a way to represent "last row" or "last column if I do not know beforehand the shape of the 2D array?
Use-Case
Below are a couple of use-cases why I need a function instead of directly using the a[:, 0]
expression:
- The caller does not have access to the array. The caller can get a desired row or column from the array by calling the
getSlice
function. - The preferred row or column needs to be pre-configured. For instance,
{a1: 'first row', a2: 'last column'}
. Botha1
anda2
may get transposed and modified many times. But at all times, I am interested only in the configured row/column of the two arrays.