简体   繁体   中英

Fastest way to replace values in a numpy array with a list

I want to read a list into a numpy array. This list is being replaced in every iteration of a loop and further operations are done on the array. These operations include element-wise subtraction from another numpy array for a distance measure, and checking a threshold condition in this distance using the numpy.all() function. Currently I am using np.array( list ) each time to convert the list to an array:

#!/usr/bin/python
import numpy as np
a = [1.33,2.555,3.444,5.666,4.555,6.777,8.888]
%timeit b = np.array(a)

100000 loops, best of 3: 4.83 us per loop

Is it possible to do anything better than this, if I know the size of the list and it is invariable? Even small improvements are welcome, as I run this a very large number of times.

I've tried %timeit(np.take(a,range(len(a)),out=b)) which takes much longer: 100000 loops, best of 3: 16.8 us per loop

As you "know the size of the list and it is invariable", you can set up an array first:

b = np.zeros((7,))

This then works faster:

%timeit b[:] = a
1000000 loops, best of 3: 1.41 µs per loop

vs

%timeit b = np.array(a)
1000000 loops, best of 3: 1.67 µs per loop

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