Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pop rows of a numpy array with delete()

With the following code, I iterate over an array in reverse order and print and pop the last item. In the end I expect to see an empty array, but it is not empty.

a = array([5,1,2,4,9,2]).reshape(-1, 1)
for j in a[::-1]:
    print(j.item())
    np.delete(a, len(a)-1, 0)
print("a=", a)

Output is

2
9
4
2
1
5
a= [[5]
 [1]
 [2]
 [4]
 [9]
 [2]]

How can I fix that? With the syntax of delete(array, pos, axis), I expect to delete the rows from last to start.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

numpy.delete does not work in place:

>>> np.delete(a, len(a)-1, 0)
array([[5],
       [1],
       [2],
       [4],
       [9]])

I am not sure why you would want to iterate over an array this way but you would need:

a = np.array([5,1,2,4,9,2]).reshape(-1, 1)
for j in a[::-1]:
    print(j.item())
    a = np.delete(a, len(a)-1, 0)  ## assign back to a
print("a=", a)

output:

2
9
4
2
1
5
a= []
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading