LearnToGrow
LearnToGrow

Reputation: 1757

How to remove empty element from numpy array

Here an example:

a = np.array([[1, 2, 3,4], [], [1,2,0,9]]) 

print(a)
# array([list([1, 2, 3, 4]), list([]), list([1, 2, 0, 9])], dtype=object)

How to remove the empty element and return only:

array([[1, 2, 3, 4], [1, 2, 0, 9]], dtype=object)

Upvotes: 3

Views: 12763

Answers (4)

Deepak Yadav
Deepak Yadav

Reputation: 41

A simple for loop iteration over array and computing length will be enough to get rid of empty elements.

a = np.array([[1,2,3,4],[],[5,6,7,8]]
output = []
for elem in a:
    if elem:
          output.append(elem)
output= np.array(output)

Upvotes: 0

Paul Panzer
Paul Panzer

Reputation: 53029

You can use logical indexing:

a[a.astype(bool)]
# array([list([1, 2, 3, 4]), list([1, 2, 0, 9])], dtype=object)

Upvotes: 7

A. Nadjar
A. Nadjar

Reputation: 2543

you can use filter:

a = np.array([[1, 2, 3,4], [], [1,2,0,9]]) 
list(filter(None, a))

# [[1, 2, 3, 4], [1, 2, 0, 9]]

Upvotes: 2

Vicrobot
Vicrobot

Reputation: 3988

You can loop over the array:-

a = np.array([[1, 2, 3,4], [], [1,2,0,9]]) 
a1 = np.array([i for i in a if i])

>>> a1
array([[1, 2, 3, 4],
       [1, 2, 0, 9]])

Upvotes: 2

Related Questions