简体   繁体   English

使用函数给出的值初始化numpy数组的最快方法

[英]Fastest way to initialize numpy array with values given by function

I am mainly interested in ((d1,d2)) numpy arrays (matrices) but the question makes sense for arrays with more axes. 我主要感兴趣的是((d1,d2))numpy数组(矩阵),但这个问题对于具有更多轴的数组是有意义的。 I have function f(i,j) and I'd like to initialize an array by some operation of this function 我有函数f(i,j),我想通过这个函数的一些操作初始化一个数组

A=np.empty((d1,d2))
for i in range(d1):
    for j in range(d2):
        A[i,j]=f(i,j)

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. 这是可读的和有效的,但我想知道是否有更快的方法,因为我的阵列A将非常大,我必须优化这一点。

One way is to use np.fromfunction . 一种方法是使用np.fromfunction Your code can be replaced with the line: 您的代码可以替换为以下行:

np.fromfunction(f, shape=(d1, d2))

This is implemented in terms of NumPy functions and so should be quite a bit faster than Python for loops for larger arrays. 这是根据NumPy函数实现的,因此对于较大的数组,它应该比Python for循环快得多。

a=np.arange(d1)
b=np.arange(d2)
A=f(a,b)

Note that if your arrays are of different size, then you have to create a meshgrid: 请注意,如果您的数组大小不同,则必须创建一个meshgrid:

X,Y=meshgrid(a,b)
A=f(X,Y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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