I would like to append elements to en empty Numpy array in-place. I know the maximum array size beforehand. I can't find a direct way to accomplish that, so here is my workaround:
N = 1000
a = np.empty([N], dtype=np.int32)
j = 0
for i in range(N):
if f(i):
a[j] = g(i)
j += 1
a.resize(j)
Is there a more elegant way to code it, without keeping track of current length in j
, similar in simplicity to C++ version below?
const int N = 1000;
vector<int> a;
a.reserve(N);
for (int i=0; i<N; i++)
if (f(i))
a.push_back(g(i));
a.shrink_to_fit();
And yes, I read How to extend an array in-place in Numpy?, but it doesn't cover this specific case, i.e. array size limit known beforehand.