Python numpy 数组的列加法与移位

标签 python arrays numpy iteration

如何使用 python numpy 数组通过移位完成列加法?

我有二维数组,需要它的扩展副本。

a = array([[0, 2, 4, 6, 8],
       [1, 3, 5, 7, 9]])

我想要类似的东西(以下是伪代码,它不起作用;据我所知,numpy中没有a.columns):

shift = 3
mult_factor = 0.7
for column in a.columns - shift :
    out[column] = a[column] + 0.7 * a[column + shift] 

我也知道,我可以使用索引做类似于我需要的事情。但我认为枚举三个值并仅使用一个 (j) 确实有点过分了:

for (i,j),value in np.ndenumerate(a):
    print i,j

我发现我可以迭代列,但不能迭代它们的索引:

for column in a.T:
    print column

尽管我可以简单地使用类似于 xrange 的东西来做到这一点,但适用于多维数组:

In [225]: for column in np.ndindex(a.shape[1]):
            print column
   .....:     
(0,)
(1,)
(2,)
(3,)
(4,)

所以现在我只知道如何使用简单的 xrange 来做到这一点,我不确定这是最好的解决方案。

out = np.zeros(a.shape)
shift = 2
mult_factor = 0.7
for i in xrange(a.shape[1]-shift):
    print a[:, i]
    out[:, i] =  a[:, i] + mult_factor * a[:, i+shift]

然而,在 Python 中它可能不会那么快。 你能给我一个建议,它的性能如何,也许有更快的方法来完成 numpy 数组的列添加与移位?

最佳答案

out = a[:, :-shift] + mult_factor * a[:, shift:]

我想这就是您要找的。它是循环的矢量化形式,对大片 a 进行操作,而不是逐列操作。

关于Python numpy 数组的列加法与移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22004430/

相关文章:

python - 如何从命令行 odoo 11 卸载/更新模块

c++ - 初始化我的数组时出错

arrays - 如何演示数组上的竞争条件

python - 采用单个对象或可迭代对象的 Python 函数中的参数名称

python - 在 Linux 上使用 Python 即时将 .doc/.docx 从 URL 转换为 .pdf

python - 当特定列相同时追加 id

python - Numpy reshape 产生不同的大小错误

PHP:使用 usort 或从 UTF-8 字符串排序字母会导致未知字符

python - 通过将非采样值归零来对 numpy 数组进行采样?

python - 是否可以使用 numpy 中可用的函数将二维数组修补到子数组的数组中?