[英]Forming an array with elements in specific positions from multiple arrays in Python
I have an array A
.我有一个数组
A
。 I want to take the first, second,...,ninth elements of each A[0],A[1],A[2]
to form a new array B
.我想将每个
A[0],A[1],A[2]
的第一个、第二个、...、第九个元素组成一个新数组B
。 I present the current and expected outputs.我介绍了当前和预期的输出。
import numpy as np
A=np.array([np.array([[1, 2, 3],
[4, 5, 6 ],
[7, 8, 9]]),
np.array([[[10, 11, 12],
[13, 14, 15 ],
[16, 17, 18]]]),
np.array([[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])], dtype=object)
for t in range(0,len(A)):
B=A[0][t][0]
print([B])
The current output is当前的 output 是
[1]
[4]
[7]
The expected output is预期的 output 是
array([[1,10,19],
[2,11,20],
[3,12,21],
[4,13,22],
[5,14,23],
[6,15,24],
[7,16,25],
[8,17,26],
[9,18,27]])
You can traverse the array, append all values as columns and transpose the resulting matrix:您可以遍历数组 append 所有值作为列并转置结果矩阵:
import numpy as np
A=np.array([np.array([[1, 2, 3],
[4, 5, 6 ],
[7, 8, 9]]),
np.array([[[10, 11, 12],
[13, 14, 15 ],
[16, 17, 18]]]),
np.array([[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])], dtype=object)
out = np.array([A[i].flatten() for i in range(len(A))]).transpose()
#out = np.array([i.flatten() for i in A]).transpose() #Second option
print(out)
Output: Output:
[[ 1 10 19]
[ 2 11 20]
[ 3 12 21]
[ 4 13 22]
[ 5 14 23]
[ 6 15 24]
[ 7 16 25]
[ 8 17 26]
[ 9 18 27]]
B = np.array([a.ravel() for a in A]).T
#array([[ 1, 10, 19],
# [ 2, 11, 20],
# [ 3, 12, 21],
# [ 4, 13, 22],
# [ 5, 14, 23],
# [ 6, 15, 24],
# [ 7, 16, 25],
# [ 8, 17, 26],
# [ 9, 18, 27]])
Your array is broken.你的阵列坏了。
If you fix it, you can deal with it a lot easier.如果你修复它,你可以更容易地处理它。
.squeeze()
shakes useless dimensions out of a numpy array. .squeeze()
从 numpy 数组中剔除无用的维度。
numpy
lets you transpose dimensions. numpy
允许您转置尺寸。
ravel
flattens an array. ravel
使数组变平。 That's a valid approach but I've chosen to do the flattening using reshape
这是一种有效的方法,但我选择使用
reshape
进行展平
a1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
a2 = np.array([[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])
a3 = np.array([[[19, 20, 21],
[22, 23, 24],
[25, 26, 27]]])
A = [a1, a2, a3]
print([a.shape for a in A])
# [(3, 3), (1, 3, 3), (1, 3, 3)]
A = [a.squeeze() for a in A]
print([a.shape for a in A])
# [(3, 3), (3, 3), (3, 3)]
A = np.array(A)
print(repr(A))
# array([[[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9]],
#
# [[10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]],
#
# [[19, 20, 21],
# [22, 23, 24],
# [25, 26, 27]]])
A.transpose((1, 2, 0)) # explicit form of A.transpose()
# array([[[ 1, 10, 19],
# [ 2, 11, 20],
# [ 3, 12, 21]],
#
# [[ 4, 13, 22],
# [ 5, 14, 23],
# [ 6, 15, 24]],
#
# [[ 7, 16, 25],
# [ 8, 17, 26],
# [ 9, 18, 27]]])
A.transpose((1, 2, 0)).reshape((-1, 3))
# array([[ 1, 10, 19],
# [ 2, 11, 20],
# [ 3, 12, 21],
# [ 4, 13, 22],
# [ 5, 14, 23],
# [ 6, 15, 24],
# [ 7, 16, 25],
# [ 8, 17, 26],
# [ 9, 18, 27]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.