[英]How to make a 2D numpy array with each element being a tuple of its indices?
[英]Replace each element of multidimensional array with tuple of respective indices
在 numpy 中,假设我有一个形状为 (2, 3, 2, 2) 的数组k
。
k = np.array([[[[-0.08759809, -0.10987781],
[-0.18387192, -0.2109216 ]],
[[ 0.21027089, 0.21661097],
[ 0.22847626, 0.23004637]],
[[ 0.50813986, 0.54309974],
[ 0.64082444, 0.67101435]]],
[[[-0.98053589, -1.03143541],
[-1.19128892, -1.24695841]],
[[ 0.69108355, 0.66880383],
[ 0.59480972, 0.56776003]],
[[ 2.36270298, 2.36904306],
[ 2.38090835, 2.38247847]]]])
如何将创建一个新的数组j
形状的(2,3,2,2),使得每个元件j
是在相应的值的索引k
?
第一个维度的第一个元素和第二个维度的第一个元素中的示例。 (对应于
[[[[-0.08759809, -0.10987781],
[-0.18387192, -0.2109216 ]],
)
[[[[(0, 0, 0, 0), (0, 0, 0, 1)],
[(0, 0, 1, 0), (0, 0, 1, 1)]],
.... 等等。
一个简单的解决方案是迭代 j 并使用其索引j[idx, :] = idx
显式填充每个元素:
k = np.round(np.random.random((4, 5)), 2)
j = np.empty(k.shape+(k.ndim,))
for idx in np.ndindex(k.shape):
j[idx, :] = idx
# array([[[0., 0.],
# [0., 1.],
# [0., 2.],
# [0., 3.],
# [0., 4.]],
# [[1., 0.],
# [1., 1.],
# [1., 2.],
# [1., 3.],
# [1., 4.]],
# [[2., 0.],
# [2., 1.],
# [2., 2.],
# [2., 3.],
# [2., 4.]],
# [[3., 0.],
# [3., 1.],
# [3., 2.],
# [3., 3.],
# [3., 4.]]])
这个想法是使用np.ndindex如下:
j = np.fromiter(np.ndindex(k.shape), dtype='i4,'*k.ndim).reshape(k.shape)
结果:
array([[[[(0, 0, 0, 0), (0, 0, 0, 1)],
[(0, 0, 1, 0), (0, 0, 1, 1)]],
[[(0, 1, 0, 0), (0, 1, 0, 1)],
[(0, 1, 1, 0), (0, 1, 1, 1)]],
[[(0, 2, 0, 0), (0, 2, 0, 1)],
[(0, 2, 1, 0), (0, 2, 1, 1)]]],
[[[(1, 0, 0, 0), (1, 0, 0, 1)],
[(1, 0, 1, 0), (1, 0, 1, 1)]],
[[(1, 1, 0, 0), (1, 1, 0, 1)],
[(1, 1, 1, 0), (1, 1, 1, 1)]],
[[(1, 2, 0, 0), (1, 2, 0, 1)],
[(1, 2, 1, 0), (1, 2, 1, 1)]]]],
dtype=[('f0', '<i4'), ('f1', '<i4'), ('f2', '<i4'), ('f3', '<i4')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.