Home > Back-end >  Deleting first and last rows of an array in Python
Deleting first and last rows of an array in Python

Time:04-11

How do I delete first and last row of an array in Python? The desired output is attached.

import numpy as np
A=np.array([[0, 1, 0, 1, 1, 0],
       [1, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 0, 1],
       [0, 0, 1, 0, 1, 0]])

Desired output:

array([[1, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 0, 1]])

CodePudding user response:

What about slicing

>>> A[1:-1, :]
array([[1, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 0, 1]])

or using numpy.delete

>>> np.delete(A, [0, -1], axis=0)
array([[1, 0, 0, 1, 0, 0],
       [0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 0],
       [1, 0, 1, 1, 0, 1]])

CodePudding user response:

try this, it will start from index 1 contrary to 0, and end with second last index which is what you want.

A[1:-1]
  • Related