简体   繁体   中英

Creating a dynamic array using numpy in python

I want to create a dynamic array without size specification. In that array, I need to insert elements at any point I require. The remaining values in them can be either null or undefined till it gets a value assigned to it.

Ex:

a = np.array([])

np.insert(a, any index value, value)

So, if I use np.insert(a, 5, 1) I should get the result as:

array([null, null, null, null, null, 1])

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM