numpy:矩阵数组移位/按索引插入 [英] Numpy: Matrix Array Shift / Insert by Index
问题描述
我有一个对象,在该对象中,我已将大量的for循环方法转换为一系列矢量化的numpy数组(速度提高了约50倍).现在,我正在尝试添加一种新方法,该方法需要处理一个numpy矩阵,然后根据矩阵中的数组索引移动"子数组内容(即插入值).我知道我可以使用for循环来完成此操作,但是我试图通过使用向量数学来提高速度来避免这种情况.
I have an object where I have converted a massive for-loop method into a series of vectorized numpy arrays (about 50x faster). Now I am trying to add a new method where I need to deal with a numpy matrix and then "shift" sub-array contents (i.e. insert values) based on the array index within the matrix. I know I can accomplish this with a for-loop, but am trying to avoid that with the speed-up gains achieved by using vector math instead.
我想知道是否有一种快速有效的方法来完成以下任务:
I was wondering if there is a fast and efficient way to accomplish the following:
import numpy as np
period = [1, 2, 3]
x = [1, 10, 100]
y = [.2, .4, .6]
z = np.outer(x,y)
print(z)
结果:
[[ 0.2 0.4 0.6]
[ 2. 4. 6. ]
[ 20. 40. 60. ]]
我想移动z中的行,以基于句点的方式将零的数量添加为z中的行索引,基本上是以下内容:
I'd like to shift the rows in z to add the number of zeros based on period as the row index in z, basically the following:
[[ 0.0 0.2 0.4 0.6 ]
[ 0.0 0.0 2.0 4.0 6.0 ]
[ 0.0 0.0 0.0 20.0 40.0 60.0 ]]
最终,我希望在垂直/列轴(轴= 1)上求和.我需要一个如下的最终数组:
Ultimately, I'd be looking to sum on the vertical / column axis (axis=1). I'd need a final array like the following:
[ 0.0 0.2 2.4 24.6 46.0 60.0]
推荐答案
您还可以先计算索引并立即分配:
You can also calculate the indices first and assign at once:
a = np.array(
[[0.2 , 0.4 , 0.6],
[2., 4., 6. ],
[20., 40., 60. ]])
s0, s1 = a.shape
rows = np.repeat(np.arange(s0), s1).reshape(a.shape)
cols = (np.add.outer(np.arange(0, s0), np.arange(s1)) + 1)
res = np.zeros((s0, s0 + s1))
res[rows, cols] = a
np.sum(res,axis=0)
>>> np.sum(res,axis=0)
array([ 0. , 0.2, 2.4, 24.6, 46. , 60. ])
这篇关于numpy:矩阵数组移位/按索引插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!