3

I have a numpy array of numpy arrays, and I want to convert it to a 2d numpy array. For example

#Init Sub Arrays
a = np.array([1,2])
b = np.array([3,4,5])
c = np.array([2,1])
d = np.array([5,4,3])

#Combine Sub Arrays
e = np.array([[a,b],[c,d]])

#Sample Sub Arrays
f = e[:,0]
#Attempt to convert sub np arrays to 2d np array
g = np.array(f)

expected = np.array([[1,2],[2,1]])
print("Actual 1: ",f)
print("Actual 2: ",g)
print("Expected:", expected)

print("Actual 1: ",np.ravel(f))
print("Actual 2: ",np.ravel(g))
print("Expected: ",np.ravel(expected))

Output:

Actual 1:  [array([1, 2]) array([2, 1])]
Actual 2:  [array([1, 2]) array([2, 1])]
Expected: [[1 2]
 [2 1]]
Actual 1:  [array([1, 2]) array([2, 1])]
Actual 2:  [array([1, 2]) array([2, 1])]
Expected:  [1 2 2 1]

I understand that the array is initialized the way it is because numpy doesn't support arrays of different length on the same dimension, but I want to know how I can convert a valid sample of a "hack" numpy array to a "valid" numpy array

1 Answer 1

3

You could just use np.vstack:

out = np.vstack(e[:,0])
print(out)
array([[1, 2],
       [2, 1]])

print(out.ravel())
array([1, 2, 2, 1])
Sign up to request clarification or add additional context in comments.

1 Comment

To build on this, if OP wants a 2 x 5 array, use hstack() inside vstack(): e = np.vstack([np.hstack([a,b]), np.hstack([c,d])])

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.