I searched for your problem and came across: Using Numpy Vectorize on Functions that Return Vectors.
So I guess you could use a vectorized approach:
import numpy as np
x = [[[1,2,3], "abs"], [[1,2,3], "abs"]]
y = np.array(x)
z = y[:, 0]
def f(l):
return np.array(l)
v = np.vectorize(f, signature='()->(n)')
k = v(z)
which gives k
as:
array([[1, 2, 3],
[1, 2, 3]])
@hpaulj also suggests a neater method using np.vstack(z)
, which gives the same answer.
According to the documentation, the argument to vstack should be a "sequence of ndarrays", so I don't think it's strictly correct to pass a sequence of lists, but I can confirm that it does work.
Finally, if it were my code I would just stick to a simple list comprehension, it is the simplest way and any solution will have to do some form of for-loop converting lists to ndarrays, so why not just do the iteration in Python.
>>> np.array([r[0] for r in x])
array([[1, 2, 3],
[1, 2, 3]])