3

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)

4 Answers 4

7

You can use logical indexing:

a[a.astype(bool)]
# array([list([1, 2, 3, 4]), list([1, 2, 0, 9])], dtype=object)
Sign up to request clarification or add additional context in comments.

Comments

2

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]])

Comments

2

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]]

Comments

0

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)

2 Comments

What's the shape and dtype of output? Compared to the original a ?
Output would be a numpy array, of shape: (numpy.ndarray, (2, 4))

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.