Numpy:用最少的操作重塑数组
我有一个包含112行和40列的数组。
我需要把它转换成40组,每组有56个点,每个点有x和y坐标。
所以,第一行是每组第一个点的x坐标。第二行是每组第二个点的x坐标……一直到第56行。之后的行就是y坐标。
1st line : 40 x's
2nd line: 40 x's
...
56th line: 40 x's
57th line: 40 y's
...
112th line: 40 y's
最开始我想用 data.reshape(40, 56, 2)
来实现,但这样不行,因为x的值在y的值之前。如果我有一行是x坐标,另一行是y坐标,那样就可以了。
编辑:
for i in xrange(len(data)/2):
points.append(data[i])
points.append(data[i+len(data)/2])
points = np.array(points).T.reshape(len(data[0]), len(data)/2, 2)
return points
2 个回答
2
我会用一个更小的数组(8行5列),这样我们可以更容易地查看返回的值。
import numpy as NP
# just create a smaller array to work with:
A = NP.random.randint(0, 10, 40).reshape(8, 5)
# split A in half, to separate x and y
p, q = NP.vsplit(A, 2)
# create a 'template' array of the correct dimension
xy = NP.zeros(2, 4, 5)
# now just map the x and y values onto the template
xy[0:,:] = p
xy[1:,:] = q
# the transformed matrix:
array([[[ 8., 5., 2., 5., 7.],
[ 2., 6., 0., 7., 2.],
[ 4., 4., 7., 5., 5.],
[ 8., 5., 2., 0., 5.]],
[[ 4., 8., 6., 9., 2.],
[ 2., 6., 5., 8., 1.],
[ 3., 2., 6., 2., 2.],
[ 1., 8., 0., 7., 3.]]])
4
这里有一个想法:
[[(data[i,j], data[i+56,j]) for i in range(56)] for j in range(40)]
这个代码会返回一个包含多个元组的列表。
补充说明:你刚才的修改让我明白了你的需求。如果你想用纯Numpy来实现,那这个代码可以用吗?
data.reshape(2, 56, 40).swapaxes(0,2)