gpt4 book ai didi

python - 将前 n 行作为列添加到 NumPy 数组

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

我想将前面的 n 行作为列添加到 NumPy 数组。

例如,如果n=2,下面的数组...

[[ 1, 2]
[ 3, 4]
[ 5, 6]
[ 7, 8]
[ 9, 10]
[11, 12]]

...应该变成下面的:

[[ 1, 2, 0, 0, 0, 0]
[ 3, 4, 1, 2, 0, 0]
[ 5, 6, 3, 4, 1, 2]
[ 7, 8, 5, 6, 3, 4]
[ 9, 10, 7, 8, 5, 6]
[11, 12, 9, 10, 7, 8]]

关于如何在 for 循环中遍历整个数组的情况下如何做到这一点,我有什么想法吗?

最佳答案

这是一个矢量化的方法-

def vectorized_app(a,n):   
M,N = a.shape
idx = np.arange(a.shape[0])[:,None] - np.arange(n+1)
out = a[idx.ravel(),:].reshape(-1,N*(n+1))
out[N*(np.arange(1,M+1))[:,None] <= np.arange(N*(n+1))] = 0
return out

sample 运行-

In [255]: a
Out[255]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])

In [256]: vectorized_app(a,3)
Out[256]:
array([[ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 4, 5, 6, 1, 2, 3, 0, 0, 0, 0, 0, 0],
[ 7, 8, 9, 4, 5, 6, 1, 2, 3, 0, 0, 0],
[10, 11, 12, 7, 8, 9, 4, 5, 6, 1, 2, 3],
[13, 14, 15, 10, 11, 12, 7, 8, 9, 4, 5, 6],
[16, 17, 18, 13, 14, 15, 10, 11, 12, 7, 8, 9]])

运行时测试-

我在计时@Psidom's loop-comprehension based method以及这篇文章中列出的矢量化方法,是问题中发布的样本的 100x 放大版本(就大小而言):

In [246]: a = np.random.randint(0,9,(600,200))

In [247]: n = 200

In [248]: %timeit np.column_stack(mypad(a, i) for i in range(n + 1))
1 loops, best of 3: 748 ms per loop

In [249]: %timeit vectorized_app(a,n)
1 loops, best of 3: 224 ms per loop

关于python - 将前 n 行作为列添加到 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38595035/

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