Slicing of a Numpy 2D Array, or How to Extract an Mxm Submatrix from an Nxn Array (N>M)

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (nm)?

As Sven mentioned, x[[[0],[2]],[1,3]] will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]] will return the values x[0,1] and x[2,3] in an array.

There is a helpful function for doing the first example I gave, numpy.ix_. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]. This can save you from having to enter in all of those extra brackets.

How to quickly select a sub matrix in a 2-dimensional matrix using numpy?

If you have the indices you could do:

x = np.array([[1,2,3], [2,3,4], [0,1,2], [4,5,6]])
y = np.array([0, 2, 4, 5])
matrix[y[:,None], x]

output:

array([[ 1,  2,  3],
[16, 17, 18],
[28, 29, 30],
[39, 40, 41]])

Numpy extract submatrix

Give np.ix_ a try:

Y[np.ix_([0,3],[0,3])]

This returns your desired result:

In [25]: Y = np.arange(16).reshape(4,4)
In [26]: Y[np.ix_([0,3],[0,3])]
Out[26]:
array([[ 0, 3],
[12, 15]])

Slice multidimensional numpy array from max in a given axis

As @hpaulj mentionned in the comments, using a[wheremax, np.arange(m)] did the trick.

Numpy multi-dimensional array slicing

You can use np.r_ to concatenate slice objects:

newarr [:,:,1:10] = oldarr[:,:,np.r_[1:7,8:11]] 

Example:

np.r_[1:4,6:8]
array([1, 2, 3, 6, 7])

Numpy common slicing for different dimensions

Use Ellipsis as below:

print(arr2d[..., -1, :])
print(arr3d[..., -1, :])

Output

[1 1]
[[1 1]
[2 7]
[8 6]
[6 5]]

From the documentation (emphasis mine):

Ellipsis expands to the number of : objects needed for the selection
tuple to index all dimensions. In most cases, this means that the
length of the expanded selection tuple is x.ndim. There may only be a
single ellipsis present

But if you want to create a function that works both for 2d and 3d arrays I suggest that you convert the 2d array two a 3d array by adding a new axis. Find a toy example below:

def foo_index(arr):
if len(arr.shape) == 2:
arr = arr[np.newaxis, :]
return arr[:, -1]

print(foo_index(arr2d)) # two-dimensional shape
print(foo_index(arr3d)) # two-dimensional shape

Note that the output now have the same shape (2d), therefore code depending on the result can work regardless of a 2d or 3d input array. Note that this will not happen by using the same slice for both arrays.

Extract 2d ndarray from arbitrarily dimensional ndarray using index arrays

I will try to provide some explainability to @Michael Szczesny answer.

First, notice that if you have an np.array with dimension n and pass m indexes where m<n, then it will be the same as using : in the dimensions >=m. In your case, for example:

dummy[(0, 0)] == dummy[0, 0, :]

Given that, note that you can also pass an array as an index. Thus:

dummy[([0, 1], [0, 0])]

It would be the same as:

np.array([dummy[(0,0)], dummy[(1,0)]])

You can validate that using:

dummy[([0, 1], [0, 0])] == np.array([dummy[(0,0)], dummy[(1,0)]])

Finally, notice that:

(*X.T,)
# (array([0, 4, 2]), array([1, 1, 0]))

You are here getting each dimension as an array, and then you will get:

[
dummy[0,1],
dummy[4,1],
dummy[2,0]
]

Which is the same as:

[
dummy[0,1,:],
dummy[4,1,:],
dummy[2,0,:]
]

Edit: Instead of using (*X.T,), you can use tuple(X.T), which for me, makes more sense



Related Topics



Leave a reply



Submit