用函数给定的值初始化numpy数组的最快方法 [英] Fastest way to initialize numpy array with values given by function
问题描述
我主要对((d1,d2))numpy数组(矩阵)感兴趣,但是这个问题对于具有更多轴的数组有意义.我有函数f(i,j),我想通过此函数的一些操作来初始化数组
I am mainly interested in ((d1,d2)) numpy arrays (matrices) but the question makes sense for arrays with more axes. I have function f(i,j) and I'd like to initialize an array by some operation of this function
A=np.empty((d1,d2))
for i in range(d1):
for j in range(d2):
A[i,j]=f(i,j)
这是可读且可行的,但是我想知道是否有一种更快的方法,因为我的数组A将非常大,因此我必须优化此位.
This is readable and works but I am wondering if there is a faster way since my array A will be very large and I have to optimize this bit.
推荐答案
One way is to use np.fromfunction
. Your code can be replaced with the line:
np.fromfunction(f, shape=(d1, d2))
这已实现在NumPy函数的术语,因此对于大型数组,它应该比Python for
循环快很多.
This is implemented in terms of NumPy functions and so should be quite a bit faster than Python for
loops for larger arrays.
这篇关于用函数给定的值初始化numpy数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!