Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete last n rows from Numpy array?

I'm trying to delete the last few rows from a numpy array. I'm able to delete 0 to i rows with the following code.

for i, line in enumerate(two_d_array1):
    if all(v == 0 for v in line):
        pass
    else:
        break

two_d_array2 = np.delete(two_d_array1, slice(0, i), axis=0)

Any suggestions on how to do the same for the end of the array?

for i, line in enumerate(reversed(two_d_array2)):
    if all(v == 0 for v in line):
        pass
    else:
        break

two_d_array3 = np.delete(two_d_array2, **slice(0, i)**, axis=0)
like image 882
Dave123 Avatar asked Feb 06 '18 00:02

Dave123


People also ask

How do I delete multiple rows in NumPy?

Delete multiple rows using slice We can delete multiple rows and rows from the numpy array by using numpy. delete() function using slicing. Where s The first argument is numpy array and the second argument is slicing and third argument is the axis =1 mean,i will delete multiple columns.

How do you remove the last number in an array in Python?

pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.


1 Answers

You can use slice notation for your indexing.

To remove the last n rows from an array:

a = np.array(range(10)).reshape(5, 2)
>>> a
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])

n = 2  # Remove last two rows of array.
>>> a[:-n, :]
array([[0, 1],
       [2, 3],
       [4, 5]])

To remove the first n rows from an array:

>>> a[n:, :]  # Remove first two rows.
array([[4, 5],
       [6, 7],
       [8, 9]])
like image 146
Alexander Avatar answered Sep 18 '22 22:09

Alexander