Simple question here:
I'm trying to get an array that alternates values (1, -1, 1, -1.....) for a given length. np.repeat just gives me (1, 1, 1, 1,-1, -1,-1, -1). Thoughts?
I like @Benjamin's solution. An alternative though is:
import numpy as np a = np.empty((15,)) a[::2] = 1 a[1::2] = -1
This also allows for odd-length lists.
EDIT: Also just to note speeds, for a array of 10000 elements
import numpy as np from timeit import Timer if __name__ == '__main__': setupstr=""" import numpy as np N = 10000 """ method1=""" a = np.empty((N,),int) a[::2] = 1 a[1::2] = -1 """ method2=""" a = np.tile([1,-1],N) """ method3=""" a = np.array([1,-1]*N) """ method4=""" a = np.array(list(itertools.islice(itertools.cycle((1,-1)), N))) """ nl = 1000 t1 = Timer(method1, setupstr).timeit(nl) t2 = Timer(method2, setupstr).timeit(nl) t3 = Timer(method3, setupstr).timeit(nl) t4 = Timer(method4, setupstr).timeit(nl) print 'method1', t1 print 'method2', t2 print 'method3', t3 print 'method4', t4
Results in timings of:
method1 0.0130500793457 method2 0.114426136017 method3 4.30518102646 method4 2.84446692467
If N = 100
, things start to even out but starting with the empty numpy arrays is still significantly faster (nl
changed to 10000)
method1 0.05735206604 method2 0.323992013931 method3 0.556654930115 method4 0.46702003479
Numpy arrays are special awesome objects and should not be treated like python lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With