2

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

2
  • Try np.vstack(z). Commented May 6, 2020 at 17:08
  • sounds good. thanks alot Commented May 6, 2020 at 18:31

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot. Both solutions are cool and np.vstack() also works even if it is sequence of list
@SACHINGURUSWAMY No problem.

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.