动态扩展一个scipy数组

5

有没有一种方法可以动态扩展scipy数组?

from scipy import sci
time = sci.zeros((n,1), 'double')

在此之后,我们能否增加time数组的大小?


sci不是标准,需要解释一下。 - David Heffernan
2个回答

5

可以使用resize方法扩展数组,但对于大型数组来说,这可能是一个缓慢的操作,因此如果可能的话,请避免使用*

例如:

import scipy as sci
n=3
time = sci.zeros((n,1), 'double')
print(time)
# [[ 0.]
#  [ 0.]
#  [ 0.]]

time.resize((n+1,2))
print(time)
# [[ 0.  0.]
#  [ 0.  0.]
#  [ 0.  0.]
#  [ 0.  0.]]

* 相反,从一开始就确定所需的数组大小,并仅针对 time 分配该形状。通常来说,过量分配比调整大小更快。


所以问题在于我事先不知道我想要的数组大小。因此,我会迭代并逐个增加数组的大小。就像这样:n = 1time = sci.zeros((1,1), 'double')for (i in something):time.resize((n+1), 'double')那么scipy库会怎么做呢?它会将先前的数组元素复制到新位置吗?因为那样会很慢。 - Harman
2
我会将数据添加到普通的Python列表(或列表的列表)中,等大小固定后再使用 time=np.array(time) 将其转换为numpy数组。 - unutbu

4

由于生成的time数组只是一个Numpy数组,您可以使用标准的Numpy方法来操作它们,例如numpy#insert,它返回一个修改后的数组,其中插入了新元素。以下是来自Numpy文档的示例用法(这里的npnumpy的缩写):

>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
    array([[1, 1],
           [2, 2],
           [3, 3]])
>>> np.insert(a, 1, 5)
    array([1, 5, 1, 2, 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
    array([[1, 5, 1],
           [2, 5, 2],
           [3, 5, 3]])

此外,numpy#insertnumpy#resize更快:
>>> timeit np.insert(time, 1, 1, 1)
    100000 loops, best of 3: 16.7 us per loop

>>> timeit np.resize(time, (20,1))
    10000 loops, best of 3: 27.1 us per loop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接