Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add "nan" to numpy array 20 times without loop

Here is my code:

import numpy as np
n = np.array([1.1,2.3,3.4])
for x in range(20):
    n = np.append(n, [np.nan])

How can I add nan to my numpy array 20 times without a loop, only using numpy's tools?

Thanks

like image 346
Michael Avatar asked Oct 23 '13 10:10

Michael


Video Answer


1 Answers

n = np.append(n, np.repeat(np.nan, 20))

[Edit] Ok, it seems that use of np.repeat is slower than use of np.zeros(20) + np.nan like in Mr E’s answer:

In [1]: timeit np.zeros(10000) + np.nan
100000 loops, best of 3: 16.1 µs per loop

In [2]: timeit np.repeat(np.nan, 10000)
10000 loops, best of 3: 70.8 µs per loop

But np.append is quicker:

In [3]: timeit np.append(n, n)
100000 loops, best of 3: 5.56 µs per loop

In [4]: timeit np.hstack((n, n))
100000 loops, best of 3: 7.87 µs per loop

So you can combine both approaches:

np.append(n, np.zeros(20) + np.nan)

This gives:

In [42]: timeit np.hstack((n, np.zeros(20) + np.nan))
100000 loops, best of 3: 13.2 µs per loop

In [43]: timeit np.append(n, np.repeat(np.nan, 20))
100000 loops, best of 3: 15.4 µs per loop

In [44]: timeit np.append(n, np.zeros(20) + np.nan)
100000 loops, best of 3: 10.5 µs per loop
like image 108
PhML Avatar answered Nov 15 '22 20:11

PhML