Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an array of alternating values in python?

Tags:

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?

like image 692
mike Avatar asked Aug 22 '11 23:08

mike


1 Answers

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.

like image 128
JoshAdel Avatar answered Sep 19 '22 12:09

JoshAdel