Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically expanding a scipy array

Tags:

python

scipy

Is there a way to dynamically expand an scipy array

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

Can we increase the size of time array after this?

like image 842
Harman Avatar asked Sep 25 '11 14:09

Harman


People also ask

Does Python have dynamic arrays?

In python, A dynamic array is an 'array' from the array module. E.g. This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization.

How do you expand an array in Python?

To expand the shape of an array, use the numpy. expand_dims() method. Insert a new array that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.


2 Answers

It's possible to expand arrays using the resize method, but it can be a slow operation for large arrays, so avoid it if possible*.

For example:

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.]]

* Instead, figure out how large an array you need from the beginning, and allocate that shape for time only once. In general it is faster to over-allocate than it is to resize.

like image 141
unutbu Avatar answered Oct 22 '22 06:10

unutbu


The resulting time array being just a Numpy Array, you can use standard Numpy methods for manipulating them, such as numpy#insert which returns a modified array with new elements inserted into it. Examples usage, from Numpy docs (here np is short for numpy) :

>>> 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]])

Also, numpy#insert is faster than numpy#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
like image 27
matehat Avatar answered Oct 22 '22 07:10

matehat