[英]numpy: reshape single 2D array of scan data into 3 2D arrays
I have an array of the following form:我有以下形式的数组:
x_1 y_1 z_1,1
x_1 y_2 z_1,2
x_1 y_3 z_1,3
... ... ...
x_1 y_n z_1,m
x_2 y_1 z_2,1
x_2 y_2 z_2,2
x_2 y_3 z_2,3
... ... ...
x_2 y_m z_2,m
... ... ...
x_n y_m z_n,m
which is scan data, so x- and y- coordinates with a measured value (z) at that coordinate.这是扫描数据,因此 x 和 y 坐标与该坐标处的测量值 (z)。 I want to plot this as a contour plot and for this need arrays similar to those produced my np.meshgrid()
.我想将其绘制为等高线图,为此需要类似于生成我的np.meshgrid()
数组。 So I need three arrays of the following form (which are all of shape: m rows by n columns):所以我需要以下形式的三个数组(它们都是形状:m 行 x n 列):
X = [x_1 x_2 x_3 ... x_n
x_1 x_2 x_3 ... x_n
... .
... .
... .
x_1 x_2 x_3 ... x_n]
Y = [y_1 y_1 y_1 ... y_1
y_2 y_2 y_2 ... y_2
... .
... .
... .
y_m y_m y_m ... y_m]
Z = [z_1,1 z_2,1 z_3,1 ... z_n,1
z_1,2 z_2,2 z_3,2 ... z_n,2
... .
... .
... .
z_1,m z_2,m z_3,m ... z_n,m]
Caveats:注意事项:
What is the most pythonic way of implementing this?实现这一点的最pythonic方式是什么? Is there a simple way by employing reshaping?有没有一种简单的方法通过使用重塑? I could do it with a for loop, keeping track of the current x- and y- coordinate and moving to a new column/row if they change, to insert values into the arrays.我可以使用 for 循环来完成,跟踪当前的 x 和 y 坐标,并在它们发生变化时移动到新的列/行,以将值插入到数组中。 But this seems very tedious and slow...但这似乎非常乏味和缓慢......
TL;DR TL; 博士data.T.reshape(3,m,n).transpose((0,2,1))
In [60]: m, n = 3, 5
...: x, y, z = (
...: np.array(list(range(m))*n).reshape(n,m).T.flatten(),
...: np.array(list(range(n))*m),
...: np.arange(n*m))
...: a = np.array((x, y, z)).T
...: print(a)
[[ 0 0 0]
[ 0 1 1]
[ 0 2 2]
[ 0 3 3]
[ 0 4 4]
[ 1 0 5]
[ 1 1 6]
[ 1 2 7]
[ 1 3 8]
[ 1 4 9]
[ 2 0 10]
[ 2 1 11]
[ 2 2 12]
[ 2 3 13]
[ 2 4 14]]
meshgrid
would like to do让我们看看meshgrid
想要做什么In [62]: np.meshgrid(range(m), range(n))
Out[62]:
[array([[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2],
[0, 1, 2]]),
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])]
In [63]: a.T.reshape(3,m,n).transpose((0,2,1))
Out[63]:
array([[[ 0, 1, 2],
[ 0, 1, 2],
[ 0, 1, 2],
[ 0, 1, 2],
[ 0, 1, 2]],
[[ 0, 0, 0],
[ 1, 1, 1],
[ 2, 2, 2],
[ 3, 3, 3],
[ 4, 4, 4]],
[[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.