1

I'm facing a simple problem where I have to delete elements from a 2-dimensional NumPy array-like m. When I try to remove an element at a certain index with delete() function, it just doesn't perform the deletion.

import numpy as np

m = np.array([[1], [1], [3]])
np.delete(m, 2)

print(m)

This code is supposed to output [[1], [1]], as it's deleting the element at index 2. But the actual output it gives is the same original array [[1] [1] [3]].

  • Why is this function not working?
  • And how can I solve it without converting the NumPy array to a Python list?

2 Answers 2

1

It's because delete function, returns a copy of changed array.
You need to do this:

import numpy as np

m = np.array([[1], [1], [3]])
m = np.delete(m, 2)
print(m)

In according to numpy documentation: Return a new array with sub-arrays along an axis deleted.
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but it's not dimensional consistent [1 1]. It should return [[1], [1]] The shape of the output is (2,) but it should be (2, 1)
Right, you can set axis. If you want get 2D shape, axis value will be (0).
0

Referring numpy documentation for np.delete :-

Returns out - ndarray A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

Correct code is

import numpy as np

m = np.array([[1], [1], [3]])
m = np.delete(m, 2,0)

print(m)

Output:

[[1] [1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.