[英]Fastest way to replace values in a numpy array with a list
I want to read a list into a numpy array. 我想将列表读入numpy数组。 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.
这些操作包括从另一个numpy数组进行逐元素减法以进行距离测量,并使用numpy.all()函数检查该距离内的阈值条件。 Currently I am using
np.array( list )
each time to convert the list to an array: 目前,我每次使用
np.array( list )
将列表转换为数组:
#!/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
我已经尝试了
%timeit(np.take(a,range(len(a)),out=b))
,它花费的时间更长: 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 VS
%timeit b = np.array(a)
1000000 loops, best of 3: 1.67 µs per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.