将2D numpy数组重新调整为3个1D数组,其中包含x、y索引。

3
我有一个由值填充的numpy 2D数组(50x50),我想将这个2D数组压缩成一列(2500x1),但是值的位置很重要。可以将索引转换为空间坐标,因此我需要另外两个(x,y)(2500x1)数组,以便检索相应值的x,y空间坐标。
例如:
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]
 ...], 

有什么提示可以做到这一点吗?我试过几种方法,但它们都没有起作用。

3个回答

1

假设您想将数组压平并重新塑形为单列,请使用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)

输出:

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])

或者简单地使用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]))

谢谢,你知道我怎么才能对空间坐标做同样的事情吗? - user3611
@user3611 确定,看编辑 - mozway
对于索引部分,使用np.unravel_index(range(a.size), a.shape)更简单。 - bb1
1
@bb1 谢谢,不错的建议!我会更新答案的! - mozway
谢谢大家的帮助!这些方法都有效! - user3611

1
根据你的例子,使用np.indices函数:
data = np.arange(2500).reshape(50, 50)
y_indices, x_indices = np.indices(data.shape)

重新塑造你的数据:
data = data.reshape(-1,1)
x_indices = x_indices.reshape(-1,1)
y_indices = y_indices.reshape(-1,1)


1
为了简单起见,让我们使用以下代码片段重新生成您的数组:
value = np.arange(6).reshape(2, 3)

首先,我们创建变量x和y,它们分别包含每个维度的索引:
x = np.arange(value.shape[0])
y = np.arange(value.shape[1])

np.meshgrid是与您描述的问题相关的方法:

xx, yy = np.meshgrid(x, y, sparse=False)

最后,使用以下代码将所有元素转换成所需的形状:
xx = xx.reshape(-1, 1)
yy = yy.reshape(-1, 1)
value = value.reshape(-1, 1)

你使用的变量名在这里并不影响答案,但是数组的形状返回的不是 (x, y) 而是 (y, x) 吗?这将使得你的 x(和 xx)实际上给出了高度(或 y 轴)的值,反之亦然。 - Edward Spencer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接