[Numpy-discussion] Adding a 2D with a 1D array...

Pauli Virtanen pav+sp@iki...
Wed Sep 9 06:19:53 CDT 2009


Wed, 09 Sep 2009 13:08:22 +0200, Ruben Salvador wrote:
> Perfect! Thank you very much :D
> 
> It's not obvious, though...I think I should read more deeply into
> Python/NumPy...but for the use I'm giving to it...
> 
> Anyway, I thought the pythonic way would be faster, but after trying
> with a size 80000 instead of 8...the for loop is faster!
> 
> Pythonic time ==> 0.36776400 seconds
> For loop time ==> 0.31708717 seconds

Doubtful:

In [1]: import numpy as np

In [2]: a = np.zeros((80000, 26))

In [3]: b = np.zeros((80000,))

In [4]: def foo():
   ...:     d = np.empty(a.shape, a.dtype)
   ...:     for i in xrange(a.shape[0]):
   ...:         d[i] = a[i] + b[i]
   ...: 

In [5]: %timeit d=a+b[:,None]
100 loops, best of 3: 18.3 ms per loop

In [6]: %timeit foo()
10 loops, best of 3: 334 ms per loop



More information about the NumPy-Discussion mailing list