Reputation: 1757
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
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
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
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
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