0

I have some numpy arrays with None in the first position.

a = [None, 1, 2, 3, 4, 5]
b = [None, 4, 3, 2, 1, 5]

I want it to become:

[1, 2, 3, 4, 5]
[4, 3, 2, 1, 5]

EDIT: I know I can do:

a = [a is not None]

But In my case I want to specifically remove a[0]

tried:

a = np.delete(a, 0)

got:

AttributeError: int' object has no attribute 'delete'
8
  • Does this answer your question? How to remove all rows in a numpy.ndarray that contain non-numeric values Commented Nov 17, 2020 at 18:35
  • arr[:, 1:] will select all but the first column. With None the array will be object dtype. Without it it could be converted to numeric dtype, as with arr[:, 1:].astype(int). Commented Nov 17, 2020 at 18:36
  • Does this answer your question? efficient way of removing None's from numpy array Commented Nov 17, 2020 at 18:36
  • It partly does, but this methods search the None's (O(n)). In my case, I know that it is in array[0]. There is not there a better way? Commented Nov 17, 2020 at 18:45
  • 1
    You have messed up the np variable. It no longer is the imported module. Start over! Commented Nov 17, 2020 at 19:21

2 Answers 2

2

a is a list:

In [61]: a = [None, 1,2,3,4]
In [62]: a
Out[62]: [None, 1, 2, 3, 4]
In [63]: a[1:]               # standard list slicing
Out[63]: [1, 2, 3, 4]

If we have an array, we can do the same slicing:

In [64]: A = np.array(a)
In [65]: A
Out[65]: array([None, 1, 2, 3, 4], dtype=object)
In [66]: A[1:]
Out[66]: array([1, 2, 3, 4], dtype=object)
In [67]: A[1:].astype(int)
Out[67]: array([1, 2, 3, 4])

With None the array is object dtype, similar to a list.

With the list, we can also us del (and remove any selected item):

In [68]: a
Out[68]: [None, 1, 2, 3, 4]
In [69]: del a[0]
In [70]: a
Out[70]: [1, 2, 3, 4]

np.delete does something similar for an array, though it isn't as efficient:

In [72]: np.delete(A, 0)
Out[72]: array([1, 2, 3, 4], dtype=object)

If np.delete doesn't work for you, it's because you've messed up np.

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

1 Comment

Slicing solved it! As for np.delete, it worked when I tested it on some random array, but for some reason it is not working in my program's array.. anyway ty!
0

Numpy just have a beautiful method. Use .delete()

Example:

n = [None, 1, 2, 3, 4, 5]
n = np.delete(n, 0)

EDIT : np stands for numpy. Use: import numpy as np

1 Comment

AttributeError: "Int" object has no attribute 'delete'

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.