Assigning a numpy array using slicing

If b is 2x2 np.ndarray and the following assignment is performed, which makes numpy in the background, that is, it will convert the list [100, 100] first to a numpy array or do it directly using the list [100,100] to fill in the values ​​in the first line b:

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

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

+7
python numpy
source share
2 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 as fast:

 - numpy way : 0.97758197784423828 - Python way: 2.1633858680725098 

This is because there is a phase in which the integers in values (which are unlimited integers) are converted to 64-bit floats. To compare only loop speed, type conversion can be done previously in setup:

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

Here is what I got:

 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 are looking for vectorized computing in Python ...

+2
source share

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

 b[1,0] = 100 b[1,1] = 100 

However, it runs faster because it uses compiled loops. (The second is to do the conversion to ddar ndarray before assigning values).

-2
source share

All Articles