python - 将零添加到长 Numpy 数组

标签 python arrays numpy

我有一个很长的一维数组,我想为其计算累积和,然后在结果数组的开头添加一个零。

import numpy as np

def padded_cumsum(x):
    cum_sum_x = np.cumsum(x)  # Creating a new array here is fine

    return np.pad(cum_sum_x, (1,0), mode='constant')  # Prepend a single zero w/ pad

x = np.array(range(2**25))
print padded_cumsum(x)

函数 padded_cumsum 将被调用数十亿次,并使用不同的数组长度,因此我试图避免任何数组复制,因为这很昂贵。此外,我不能通过在开头/结尾用额外的值/NaN 实例化原始数组 x 来改变它。由于 cum_sum_x 无论如何都需要创建,我怀疑我可以通过做一些骇人听闻的事情来潜入零:

def padded_cumsum(x):
    cum_sum_x = np.empty(x.shape[0]+1)
    cum_sum_x[0] = 0 
    cum_sum_x[1:] = np.cumsum(x)

    return np.pad(cum_sum_x, (1,0), mode='constant')  # Prepend a single zero w/ pad

最佳答案

在手动分配的数组上使用 out 关键字。

out = np.empty(len(x)+pad, dtype=yourdtype)
np.cumsum(x, out=out[pad:])
out[:pad] = 0

关于python - 将零添加到长 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42418943/

相关文章:

python - 使用 np.random.rand 划分训练/测试数据

python - 来自 sklearn.datasets.make_classification 的 y

python - numpy 中的共轭转置运算符 ".H"

Javascript,具有设置生命周期的对象?

javascript - 如何使用javascript从对象数组中获取键的唯一值?

不同维度的Python zip numpy数组

python - EC.element_to_be_clickable 和 EC.presence_of_element_located to click() 一个元素的区别

python - Pandas 中更快的应用方法

python - 何时使用 Celery 组进行扇出与延迟

python - 使用多处理模块填充复杂的 numpy 数组