首页 > 解决方案 > 如何在numpy数组上映射函数

问题描述

我希望能够在标量 numpy 1-D 数组或 numpy 2-D 数组上应用通用函数。恰当的例子是

def stress2d_lefm_cyl(KI, r, qdeg) :
    """Compute stresses in Mode I around a 2D crack, according to LEFM
    q should be input in degrees"""
    sfactor = KI / sqrt(2*pi*r)
    q = radians(qdeg)
    q12 = q/2;        q32 = 3*q/2;
    sq12 = sin(q12);  cq12 = cos(q12);
    sq32 = sin(q32);  cq32 = cos(q32);
    af11 = cq12 * (1 - sq12*sq32);  af22 = cq12 * (1 + sq12*sq32);
    af12 = cq12 * sq12 * cq32
    return sfactor * np.array([af11, af22, af12])

def stress2d_lefm_rect(KI, x, y) :
    """Compute stresses in Mode I around a 2D crack, according to LEFM
    """
    r = sqrt(x**2+y**2)   <-- Error line
    q = atan2(y, x)
    return stress2d_lefm_cyl(KI, r, degrees(q))

delta = 0.5
x = np.arange(-10.0, 10.01, delta)
y = np.arange(0.0, 10.01, delta)
X, Y = np.meshgrid(x, y)
KI = 1
# I want to pass a scalar KI, and either scalar, 1D, or 2D arrays for X,Y (of the same shape, of course)
Z = stress2d_lefm_rect(KI, X, Y)

TypeError: only size-1 arrays can be converted to Python scalars

(我的意思是用它来绘制等高线图)。如果我现在改为

def stress2d_lefm_rect(KI, x, y) :
    """Compute stresses in Mode I around a 2D crack, according to LEFM
    """
    r = lambda x,y: x**2 + y**2   <-- Now this works
    q = lambda x,y: atan2(y, x)   <-- Error line
    return stress2d_lefm_cyl(KI, r(x,y), degrees(q(x,y)))
Z = stress2d_lefm_rect(KI, X, Y)

TypeError: only size-1 arrays can be converted to Python scalars

归结为

x = np.array([1.0, 2, 3, 4, 5])
h = lambda x,y: atan2(y,x)  <-- Error
print(h(0,1))   <-- Works
print(h(x, x))  <-- Error

1.5707963267948966

TypeError: only size-1 arrays can be converted to Python scalars

发布了一个“类似”问题,最有效的方法是在 numpy 数组上映射函数 。区别在于:1.我必须(或可能更多)参数(xy),它们应该具有相同的形状。2. 我还结合了一个标量参数 ( KI)。3.atan2似乎不如**2. 我的意思是使用通用函数。4. 我正在链接两个函数。

这可以解决吗? 也许可以通过在其他地方乘以结果来克服第 2 点。

标签: pythonarraysfunctionnumpylambda

解决方案


您应该使用 numpy 将您的函数应用于数组的每个元素。

前任 :

import numpy as np
np.sqrt(np.square(x) + np.square(y))


推荐阅读