1

This is a simple example of the big array

   x = [[[1,2,3], "abs"], [[1,2,3], "abs"]]
   y = np.array(x)
   z = y[:, 0]
   z.astype('int') # This will throw an error

Output

z >> Out[9]: array([list([1, 2, 3]), list([1, 2, 3])], dtype=object)

is there any way I can convert this from object to int without doing iteration over list x

1 Answers1

0

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]])
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54