Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array assignment using slicing

Tags:

python

numpy

If b is a 2x2 np.ndarray and the following assignment is performed, what does numpy do in the background, i.e. does it convert the list[100, 100] first to a numpy array or does it directly use the list[100,100] to fill in the values in the first row of b:

 b[1,:] = [100,100]

Where in the documentation can I find more information about this?

like image 220
methane Avatar asked May 13 '14 18:05

methane


1 Answers

To evaluate the speed of execution, we will use the timeit library.

import timeit
import numpy as np

setup = """
import numpy as np
tmp = np.empty(shape=(1, 100))
values = [i for i in xrange(100)]
"""

stmt1 = """tmp[0, :] = values"""
stmt2 = """
for i, val in enumerate(values):
    tmp[0, i] = val
"""

time1 = timeit.Timer(setup=setup, stmt=stmt1)
time2 = timeit.Timer(setup=setup, stmt=stmt2)

print "numpy way :", time1.timeit(number=100000)
print "Python way:", time2.timeit(number=100000)

You can test this and you will notice that numpy loops are twice faster :

- numpy way : 0.97758197784423828
- Python way: 2.1633858680725098

This is because there is a phase where the integers in values (which are unlimited integers) are converted into floats of 64 bits. In order to compare only the speed of the loops, the type conversion can be done preliminarily in the setup:

values = np.array([i for i in xrange(100)], dtype=np.float64)

Here is what I obtained :

numpy way : 0.131125926971
Python way: 2.64055013657

We notice that numpy loops are 20 times faster than Python loops.

You will find more information if you look for vectorized computations in Python ...

like image 80
Taha Avatar answered Nov 09 '22 14:11

Taha