我有一个numpy数组的numpy数组,我想将它转换为2d numpy数组。例如
#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))
输出:
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]
我知道数组是按原样初始化的,因为numpy不支持同一维度上不同长度的数组,但我想知道如何转换" hack&的有效样本#34; numpy数组到"有效" numpy数组
答案 0 :(得分:3)
您可以使用np.vstack
:
out = np.vstack(e[:,0])
print(out)
array([[1, 2],
[2, 1]])
print(out.ravel())
array([1, 2, 2, 1])