[英]Convert numpy array of arrays to a 2D numpy array
I have a numpy array of numpy arrays, and I want to convert it to a 2d numpy array. 我有一个numpy数组的numpy数组,我想将其转换为2d numpy数组。 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 我了解该数组的初始化方式是因为numpy在同一维上不支持长度不同的数组,但是我想知道如何将“ hack” numpy数组的有效样本转换为“ valid” numpy数组
You could just use np.vstack
: 您可以只使用
np.vstack
:
out = np.vstack(e[:,0])
print(out)
array([[1, 2],
[2, 1]])
print(out.ravel())
array([1, 2, 2, 1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.