I need to create a NumPy array of length n
, each element of which is v
.
Is there anything better than:
a = empty(n)
for i in range(n):
a[i] = v
I know zeros
and ones
would work for v = 0, 1. I could use v * ones(n)
, but it won't work when would be much slower.v
is None
, and also
a = np.zeros(n)
in the loop is faster thana.fill(0)
. This is counter to what I expected since I thoughta=np.zeros(n)
would need to allocate and initialize new memory. If anyone can explain this, I would appreciate it. – user3731622v * ones(n)
is still horrible, as it uses the expensive multiplication. Replace*
with+
though, andv + zeros(n)
turns out to be surprisingly good in some cases (stackoverflow.com/questions/5891410/…). – maxvar = np.empty(n)
and then to fill it with 'var[:] = v'. (btw,np.full()
is as fast as this) – Camion