Creating a dynamic array using numpy in python

Creating a dynamic array using numpy in python

In MATLAB/Octave you can create and extend a matrix with indexing:

>> a = []
a = [](0x0)
>> a(5) = 1
a =
   0   0   0   0   1

That is if you index a slot beyond the current end, it expands the matrix, and fills it with 0s.

Javascript (in a Nodejs session) does something similar

> var a = [1,2];
undefined
> a
[ 1, 2 ]
> a[6] = 1
1
> a
[ 1, 2, , , , , 1 ]
> a[3]
undefined

Leaving the intermediate slots undefined.

A Python dictionary can grow simply by indexing

In [113]: a = {0:1, 1:2}
In [114]: a[5]=1
In [115]: a
Out[115]: {0: 1, 1: 2, 5: 1}
In [116]: a[3]
...
KeyError: 3
In [117]: a.get(3,None)

Dictionaries also implement a setdefault, and a defaultdict.

A Python list grows by append and extend

In [120]: a = [1,2]
In [121]: a.append(3)
In [122]: a
Out[122]: [1, 2, 3]
In [123]: a.extend([0,0,0,1])
In [124]: a
Out[124]: [1, 2, 3, 0, 0, 0, 1]

Lists also change size with del and sliced assignment, e.g. a[1:2] = [0,0,0,2].

A numpy array is fixed in size. To grow one, you have to make a new array by concatenation

In [125]: a = np.arange(3)
In [126]: a
Out[126]: array([0, 1, 2])
In [127]: a = np.concatenate((a, [0,0,1]))
In [128]: a
Out[128]: array([0, 1, 2, 0, 0, 1])

Array functions like append, stack, delete and insert use some form of concatenate or allocate-n-fill.

In restricted cases an array can be resized (but this method is not used very often):

In [161]: a.resize(10)
In [162]: a[-1]=10
In [163]: a
Out[163]: array([ 0,  1,  2,  0,  0,  1,  0,  0,  0, 10])

Check out this package.

from numpy_da import DynamicArray

data = DynamicArray(shape=2, index_expansion=True)
data[5] = 1
print(data)  # [0, 0, 0, 0, 0, 1]

index_expansion option allows the array to grow if you index beyond the current largest index.

Creating a dynamic array using numpy in python

Leave a Reply

Your email address will not be published. Required fields are marked *