SKPS
SKPS

Reputation: 5847

How to clip a numpy array?

I have a 5x5 matrix:

>>> import numpy as np
>>> x=np.random.rand(5,5)
>>> x
array([[ 0.47231299,  0.02139265,  0.05321461,  0.06338545,  0.98003833],
       [ 0.81340571,  0.81404643,  0.87641499,  0.29969447,  0.13871426],
       [ 0.91088258,  0.02642179,  0.03657303,  0.91060929,  0.2442742 ],
       [ 0.55178147,  0.54428098,  0.21511229,  0.2177599 ,  0.52179989],
       [ 0.29138135,  0.06855664,  0.63419486,  0.154126  ,  0.1939914 ]])

I want to clip this matrix. Let's say I want the data without first and last row and also without first and last column. How to do this?

This might seem like a basic question. However, I could not understand how indexing works for 2D or multidimensional matrix, so that clipping can be done accordingly.

Upvotes: 0

Views: 2063

Answers (1)

akuiper
akuiper

Reputation: 215137

Basic numpy indexing/slicing:

x[1:-1,1:-1]

#array([[ 0.81404643,  0.87641499,  0.29969447],
#       [ 0.02642179,  0.03657303,  0.91060929],
#       [ 0.54428098,  0.21511229,  0.2177599 ]])

Upvotes: 3

Related Questions