简体   繁体   中英

numpy array assignment using slicing

If b is a 2x2 np.ndarray and the following assignment is performed, what does numpy do in the background, ie 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?

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 ...

b[1,:] = [100,100] is exactly the same as

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

It is however faster to execute as it uses compiled loops. (The second one needs to do a conversion to the ndarray dtype before attributing the values).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM