Given that a numpy
array is stored contiguously, if we try to append
or extend
to it then this happens not in-place but, instead, a new copy of the array is created with adequate 'room' for the append
or extend
to occur contiguously (see https://stackoverflow.com/a/13215559/3286832).
To avoid that, and assuming we are lucky enough to know the specific number of elements we expect the array to have, we can create a numpy
array with a fixed size filled with zeros:
import numpy as np
a = np.zeros(shape=(100,)) # [0. 0. 0. ... 0. 0. 0.]
Say that we want to populate this array each element with a new value each time (e.g. provided by the user) by editing this array in-place:
pos = 0
a[pos] = 0.002 # [0.002 0. 0. ... 0. 0. 0.]
pos = pos + 1
a[pos] = 0.101 # [0.002 0.101 0. ... 0. 0. 0.]
# etc.
pos = -1
a[pos] = 42.00 # [0.002 0.101 ... ... ... 42.]
Question:
Is there a way to keep track of the next available position pos
(i.e. last position not previously populated with a new input value) instead of manually incrementing pos
each time?
Is there a way in efficiently achieving this in numpy
, preferably? Or is there a way of achieving this in another Python library (e.g. scipy
or Pandas
)?
(edited the question according the comments and initial answers which stated how not clear my initial question was phrased - hope this now is clearer)