[Numpy-discussion] fastest way to make two vectors into an array

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Jan 30 11:26:05 CST 2003


>>>>> "John" == John Hunter <jdhunter at ace.bsd.uchicago.edu> writes:

    John> I have two equal length 1D arrays of 256-4096 complex or
    John> floating point numbers which I need to put into a
    John> shape=(len(x),2) array.

    John> I need to do this a lot, so I would like to use the most
    John> efficient means.  Currently I am doing:

I tested all the suggested methods and the transpose with [x] and [y]
was the clear winner, with an 8 fold speed up over my original code.
The concatenate method was between 2-3 times faster.

Thanks to all who responded,
John Hunter

cruncher2:~/python/test> python test.py test_naive
test_naive 0.480427026749
cruncher2:~/python/test> python test.py test_concat
test_concat 0.189149975777
cruncher2:~/python/test> python test.py test_transpose
test_transpose 0.0698409080505


from Numeric import transpose, concatenate, reshape, array, zeros
from RandomArray import normal
import time, sys

def test_naive(x,y):
    "Naive approach"
    X = zeros( (len(x),2), typecode=x.typecode())
    X[:,0] = x
    X[:,1] = y

def test_concat(x,y):
    "Thanks to Chris Barker and Bryan Cole"
    X = concatenate( ( reshape(x,(-1,1)), reshape(y,(-1,1)) ), 1)


def test_transpose(x,y):
    "Thanks to Joachim Saul"
    X = transpose(array([x]+[y]))


m = {'test_naive' : test_naive,
     'test_concat' : test_concat,
     'test_transpose' : test_transpose}

nse1 = normal(0.0, 1.0, (4096,))
nse2 = normal(0.0, 1.0, nse1.shape)

N = 1000

trials = range(N)

func = m[sys.argv[1]]
t1 = time.time()
for i in trials:
    func(nse1,nse2)
t2 = time.time()
print sys.argv[1], t2-t1







More information about the Numpy-discussion mailing list