gpt4 book ai didi

python - 按索引选择不同形状的numpy数组并将其写回

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:24 26 4
gpt4 key购买 nike

我正在寻找索引策略,如何从原始数组(左侧)中选择子数组(右侧),然后用子数组替换原始数组数组(底部)。有为每一行选择的索引,例如第一行是 [1,3,0],最后一行是 [4,6,2]。下图的完整选择矩阵如下所示:

[[1,3,0],
[2,3,2],
[4,0,6],
[1,4,0],
[4,6,2]]

到目前为止,我只能循环遍历原始数组的行并替换列索引处的值。 有不用循环的解法吗?

         +--------------------------------------+
| |
| +-----------------------+ |
| | | |
| +----------------------------+ | |
| | | | | |
| | | | | |
| | | | | |
| | | | | |
+ + + v v v
array([[ 0, 1, 2, 3, 4, 5, 6], 1, 3, 0,
[ 7, 8, 9, 10, 11, 12, 13], 9,10,9,
!14, 15, 16, 17,!18, 19,!20], 18,14,20,
[21, 22, 23, 24, 25, 26, 27], 22,25,21,
[28, 29, 30, 31, 32, 33, 34]]) 32,34,30
+ + + ^ ^ ^
| | | | | |
| +----------------+ | |
| | | |
| +-----------+ |
| |
+-------------------------------+

最终数组是原始数组,替换了子数组中的最后一个索引(从原始数组中选择。

                       +------------+
array([[ 0, 1, 2, 3,| 1, 3, 0],|
[ 7, 8, 9, 10,| 9, 10, 9],|
[14, 15, 16, 17,|18, 14, 20],|
[21, 22, 23, 24,|22, 25, 21],|
[28, 29, 30, 31,|32, 34, 30]]|
+------------+

循环解决方案:

selection = np.array([[1,3,0],
[2,3,2],
[4,0,6],
[1,4,0],
[4,6,2]])
y = np.arange(35).reshape(5,7)
s = y.shape[1] - selection.shape[1]
e = y.shape[1]
for i in range(0, y.shape[0]):
y[i, s:e] = y[i, selection[i]]

>>> y
array([[ 0, 1, 2, 3, 1, 3, 0],
[ 7, 8, 9, 10, 9, 10, 9],
[14, 15, 16, 17, 18, 14, 20],
[21, 22, 23, 24, 22, 25, 21],
[28, 29, 30, 31, 32, 34, 30]])

最佳答案

使用广播和高级索引:

>>> y[:, 4:] = y[np.arange(5)[:, None], selection]
>>> y
array([[ 0, 1, 2, 3, 1, 3, 0],
[ 7, 8, 9, 10, 9, 10, 9],
[14, 15, 16, 17, 18, 14, 20],
[21, 22, 23, 24, 22, 25, 21],
[28, 29, 30, 31, 32, 34, 30]])

关于python - 按索引选择不同形状的numpy数组并将其写回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48931971/

26 4 0