How to remove integers from a mixed numpy array containing sub-arrays and integers?

36 views Asked by At

I have a numpy array that contains both sub-arrays and an integer:

mixed_array = np.array([np.array([1, 2]), np.array([1, 2]), 0])

I want to mask the array so that I am left with only the sub-arrays and not the integer.

mixed_array = np.array([np.array([1, 2]), np.array([1, 2]))

I am working with very large arrays so I can't afford to use loops.

I have tried indexing in various ways on ~is_instance() and .dtype attributes. The mixed array is created by a useful package function, so it's hard to avoid creating it.

Edit: would it be possible to convert the ints to arrays (such as: np.array([0]) for the example above?

1

There are 1 answers

0
mozway On

Since an object array is no better than a python list, you have to use a loop:

out = np.array([a for a in mixed_array if isinstance(a, np.ndarray)])

You can vectorize this, but it won't be more efficient:

isarray = np.vectorize(lambda x: isinstance(x, np.ndarray))
out = mixed_array[isarray(mixed_array)]

Output:

array([array([1, 2]), array([1, 2])], dtype=object)

Always avoid to create object arrays in the first place.