[英]Reshape 2D numpy array into 3 1D arrays with x,y indices
I have a numpy 2D array (50x50) filled with values.我有一个 numpy 二维数组 (50x50) 填充了值。 I would like to flatten the 2D array into one column (2500x1), but the location of these values are very important.
我想将二维数组展平为一列(2500x1),但这些值的位置非常重要。 The indices can be converted to spatial coordinates, so I want another two (x,y) (2500x1) arrays so I can retrieve the x,y spatial coordinate of the corresponding value.
索引可以转换为空间坐标,所以我想要另外两个 (x,y) (2500x1) arrays 以便我可以检索相应值的 x,y 空间坐标。
For example:例如:
My 2D array:
--------x-------
[[0.5 0.1 0. 0.] |
[0. 0. 0.2 0.8] y
[0. 0. 0. 0. ]] |
My desired output:
#Values
[[0.5]
[0.1]
[0. ]
[0. ]
[0. ]
[0. ]
[0. ]
[0.2]
...],
#Corresponding x index, where I will retrieve the x spatial coordinate from
[[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
...],
#Corresponding y index, where I will retrieve the x spatial coordinate from
[[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]
...],
Any clues on how to do this?关于如何做到这一点的任何线索? I've tried a few things but they have not worked.
我尝试了几件事,但没有奏效。
Assuming you want to flatten and reshape into a single column, use reshape
:假设您要展平并重塑为单列,请使用
reshape
:
a = np.array([[0.5, 0.1, 0., 0.],
[0., 0., 0.2, 0.8],
[0., 0., 0., 0. ]])
a.reshape((-1, 1)) # 1 column, as many row as necessary (-1)
output: output:
array([[0.5],
[0.1],
[0. ],
[0. ],
[0. ],
[0. ],
[0.2],
[0.8],
[0. ],
[0. ],
[0. ],
[0. ]])
y,x = a.shape
np.tile(np.arange(x), y)
# array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
np.repeat(np.arange(y), x)
# array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
or simply using unravel_index
:或简单地使用
unravel_index
:
Y, X = np.unravel_index(range(a.size), a.shape)
# (array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]),
# array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))
For the simplisity let's reproduce your array with this chunk of code:为了简单起见,让我们用这段代码重现你的数组:
value = np.arange(6).reshape(2, 3)
Firstly, we create variables x, y which contains index for each dimension:首先,我们创建变量 x, y,其中包含每个维度的索引:
x = np.arange(value.shape[0])
y = np.arange(value.shape[1])
np.meshgrid is the method, related to the issue you described: np.meshgrid 是与您描述的问题相关的方法:
xx, yy = np.meshgrid(x, y, sparse=False)
Finaly, transform all elements it in the shape you want with these lines:最后,使用以下几行将所有元素转换为您想要的形状:
xx = xx.reshape(-1, 1)
yy = yy.reshape(-1, 1)
value = value.reshape(-1, 1)
According to your example, with np.indices
:根据您的示例,使用
np.indices
:
data = np.arange(2500).reshape(50, 50)
y_indices, x_indices = np.indices(data.shape)
Reshaping your data:重塑数据:
data = data.reshape(-1,1)
x_indices = x_indices.reshape(-1,1)
y_indices = y_indices.reshape(-1,1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.