14

I have a numpy array and I want to delete the first 3 elements of the array. I tried this solution:

           a = np.arange(0,10)
           i=0
           while(i<3):
             del a[0]
             i=i+1

This gives me an error that "ValueError: cannot delete array elements". I do not understand why this is the case. i'd appreciate the help thanks!

4 Answers 4

23

Numpy arrays have a fixed size, hence you cannot simply delete an element from them. The simplest way to achieve what you want is to use slicing:

a = a[3:]

This will create a new array starting with the 4th element of the original array.

For certain scenarios, slicing is just not enough. If you want to create a subarray consisting of specific elements from the original array, you can use another array to select the indices:

>>> a = arange(10, 20)
>>> a[[1, 4, 5]]
array([11, 14, 15])

So basically, a[[1,4,5]] will return an array that consists of the elements 1,4 and 5 of the original array.

Sign up to request clarification or add additional context in comments.

4 Comments

@Neil: You are right. That was actually my first version, but then, for some twisted reason, I changed it to 4.
to be correct: basic slicing does not create a new array, but a new view onto the underlying data, see docs.scipy.org/doc/numpy/reference/arrays.indexing.html which is one reason why numpy is as fast as C code in many cases.
@rock: Correct! I had this confused with regular Python, which does indeed create a new array.
If you want to replace the underlying data with the view, use deepcopy from the copy package` to do a = deepcopy(a[3:])
16

It works for me:

import numpy as np
a = np.delete(a, k)

where "a" is your numpy arrays and k is the index position you want delete.

Hope it helps.

Comments

1

numpy arrays don't support element deletion. Why don't you just use slicing to achieve what you want?

a = a[3:]

Comments

-1

You can convert it into a list and then try regular delete commands like pop, del, eg.

a = np.array([1,2,3,4,5])
l = list(a)
l.pop(3)
l
>>[1, 2, 3, 5]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.