How to convert an object array to a normal array in python
46,307
Solution 1
Use numpy.concatenate
:
>>> arr = array([array([[2.4567]],dtype=object),array([[3.4567]],dtype=object),array([[4.4567]],dtype=object),array([[5.4567]],dtype=object),array([[6.4567]], dtype=object)])
>>> np.concatenate(arr).astype(None)
array([[ 2.4567],
[ 3.4567],
[ 4.4567],
[ 5.4567],
[ 6.4567]])
Solution 2
You can use np.stack, works also for the multi dimensional case:
import numpy as np
from numpy import array
arr = array([array([[2.4567]],dtype=object),array([[3.4567]],dtype=object),array([[4.4567]],dtype=object),array([[5.4567]],dtype=object),array([[6.4567]],
dtype=object)])
np.stack(arr).astype(None)
array([[[2.4567]],
[[3.4567]],
[[4.4567]],
[[5.4567]],
[[6.4567]]])
Author by
Shashank
Updated on June 07, 2020Comments
-
Shashank almost 4 years
I have an object array which looks something like this
array([array([[2.4567]],dtype=object), array([[3.4567]],dtype=object), array([[4.4567]],dtype=object), array([[5.4567]],dtype=object) ... array([[6.4567]],dtype=object))
This is just an example, actual one is much bigger.
So, how do I convert this into a normal floating value numpy array.
-
Shashank almost 9 yearswhat if the above array I mentioned is just the first row of a multi dimensional array and there are several rows. "np.concatenate" joins all of them into a 1d array which I do not want. So how to concatenate them rowwise without using for loops?
-
Darcy almost 5 yearsI have the same problem as @Shashank. The above method does not work for N x M arrays.
-
Ashwini Chaudhary almost 5 years@Darcy then ask a new question instead of downvoting existing ones. o_O