1

I have a NumPy array

[None, None, None, None, 1, 2, None, 4, None]

The output I want is

[1, 2, None, 4, None]

I wrote this while loop but there is something wrong I guess

index = 0
while(numpyArray[index] is None):
    numpyArray = np.delete(numpyArray, index)
    index += 1

The output I am getting is

[None, None, 1, 2, None, 4, None]

3 Answers 3

1

The problem is that after you delete an item at position index, all subsequent indices will be shifted to the left by 1:

 0  1  2  3
[a, b, c, d]

deleting at index == 1 will cause:

 0  1  2
[a, c, d]

so that right after the deletion c and d have index -1 of what they had before the deletion. The indexing is always contiguous.


So, in your code you first delete the item at position 0, all indexes gets shifted by -1 and when you advance the index, you are now considering not the second element (the one that originally was at index == 1) but the the third element (the one that originally was at index == 2), etc.

If you leave out the index += 1 line, the code should work.


Finally, please note that NumPy arrays are not particularly efficient at resizing. Python lists are generally faster at resizing.

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

1 Comment

I can't accept it @norok2 because of low reputation but it works, Thank you so much!! :D
0

You shouldn't delete elements from a list (or, as it happens, numpy.array) while iterating over it. Instead, create a copy:

import itertools
newArray = np.array(list(itertools.dropwhile(lambda x: x is None, numpyArray)))

1 Comment

The original code was not iterating over it, though. That would have been something like for item in items: ...
0

This is not the correct way to do this in python, try use one of the following

numpyArray = [i for i in numpyArray if i is not None]

or

numpyArray = np.array(list(filter(lambda i: i is not None, numpyArray)))

1 Comment

These will remove all Nones, not just leading ones.

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.