gpt4 book ai didi

python - 我可以向量化这个二维数组索引,其中第二维取决于第一维的值吗?

转载 作者:行者123 更新时间:2023-12-01 05:55:00 25 4
gpt4 key购买 nike

在下面的示例中,我有一个 2D 数组,其中有一些经过移位和填充的实际结果。移位取决于行(填充用于根据 numpy 的要求使数组成为矩形)。是否可以在不使用 Python 循环的情况下提取真实结果?

import numpy as np

# results are 'shifted' where the shift depends on the row
shifts = np.array([0, 8, 4, 2], dtype=int)
max_shift = shifts.max()
n = len(shifts)

t = 10 # length of the real results we care about

a = np.empty((n, t + max_shift), dtype=int)
b = np.empty((n, t), dtype=int)

for i in range(n):
a[i] = np.concatenate([[0] * shifts[i], # shift
(i+1) * np.arange(1, t+1), # real data
[0] * (max_shift - shifts[i]) # padding
])
print "shifted and padded\n", a

# I'd like to remove this Python loop if possible
for i in range(n):
b[i] = a[i, shifts[i]:shifts[i] + t]

print "real data\n", b

最佳答案

您可以使用两个数组来获取数据:

a[np.arange(4)[:, None], shifts[:, None] + np.arange(10)]

或者:

i, j = np.ogrid[:4, :10]
a[i, shifts[:, None]+j]

这在 NumPy 文档中称为高级索引。

关于python - 我可以向量化这个二维数组索引,其中第二维取决于第一维的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com