Python:将函数应用于numpy 3d数组中的每个条目 [英] Python: Apply function to every entry in numpy 3d array

查看:242
本文介绍了Python:将函数应用于numpy 3d数组中的每个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在形状为x,y,z =(4,4,3)的3d numpy数组上应用一个(更复杂的函数). 假设我有以下数组:

I would like to apply a (more complex?) function on my 3d numpy array with the shape x,y,z = (4,4,3). Let's assume I have the following array:

array = np.arange(48)
array = array.reshape([4,4,3])

现在,我想在数组的每个点上调用以下函数:

Now I would like to call the following function on each point of the array:

p(x,y,z)= a(z)+ b(z)* ps(x,y)

我们假设a和b是以下1d数组,分别是ps和2d数组.

Let's assume a and b are the following 1d arrays, respectively ps a 2d array.

a = np.random.randint(1,10, size=3)
b = np.random.randint(1,10, size=3)
ps = np.arrange(16)
ps = ps.reshape([4,4])

我的直观方法是遍历数组并在每个点上调用该函数.它可以工作,但是当然太慢了:

My intuitive approach was to loop over my array and call the function on each point. It works, but of course it's way too slow:

def calcP(a,b,ps,x,y,z):
    p = a[z]+b[z]*ps[x,y]
    return p

def stupidLoop(array, a, b, ps, x, y, z):
    dummy = array
    for z in range (0, 3):
        for x in range (0, 4):
            for y in range (0, 4):
                dummy[x,y,z]=calcP(a,b,ps,x,y,z)
    return dummy

updatedArray=stupidLoop(array,a, b, ps, x, y, z)

有更快的方法吗?我知道它可以与向量化函数一起使用,但是我无法弄清楚.

Is there a faster way? I know it works with vectorized functions, but I cannot figure it out with mine.

我实际上并没有尝试使用这些数字.这只是为了说明我的问题.它来自气象界,并且有点复杂.

I didn't actually try it with these numbers. It's just to exemplify my problem. It comes from the Meteorology world and is a little more complex.

推荐答案

您可以使用numpy.fromfunction():

import numpy as np

a = np.random.randint(1,10, size=3)
b = np.random.randint(1,10, size=3)
ps = np.arange(16)
ps = ps.reshape([4,4])

def calcP(x,y,z,a=a,b=b,ps=ps):
    p = a[z]+b[z]*ps[x,y] + 0.0
    return p

array = np.arange(48)
array = array.reshape([4,4,3])

updatedArray = np.fromfunction(calcP, (4,4,3), a=a,b=b,ps=ps, dtype=int)
print (updatedArray)

请注意,我对您的函数calcP做了一些修改,以适应实际情况.另外,我添加了0.0,以确保输出数组为float s,而不是int s.

Notice that I've modified your function calcP slightly, to take kwargs. Also, I've added 0.0, to ensure that the output array will be of floats and not ints.

此外,请注意,fromfunction()的第二个参数仅指定网格的形状,在该网格上将调用功能calcP().

Also, notice that the second argument to fromfunction() merely specifies the shape of the grid, over which the function calcP() is to be invoked.

输出(由于randint的不同,每次都会有所不同):

[[[  8.   5.   3.]
  [  9.   6.  12.]
  [ 10.   7.  21.]
  [ 11.   8.  30.]]

 [[ 12.   9.  39.]
  [ 13.  10.  48.]
  [ 14.  11.  57.]
  [ 15.  12.  66.]]

 [[ 16.  13.  75.]
  [ 17.  14.  84.]
  [ 18.  15.  93.]
  [ 19.  16. 102.]]

 [[ 20.  17. 111.]
  [ 21.  18. 120.]
  [ 22.  19. 129.]
  [ 23.  20. 138.]]]

这篇关于Python:将函数应用于numpy 3d数组中的每个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆