【问题标题】:How to map a function over numpy array如何在numpy数组上映射函数
【发布时间】:2019-12-17 15:44:46
【问题描述】:

我希望能够在标量 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

发布了一个“类似”问题,Most efficient way to map function over numpy array 区别在于: 1. 我必须(或可能更多)参数(x,y),它们应该具有相同的形状。 2. 我还结合了一个标量参数 (KI)。 3.atan2 似乎比**2 更不“宽容”。我的意思是使用通用函数。 4. 我正在链接两个函数。

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

【问题讨论】:

标签: python arrays function numpy lambda


【解决方案1】:

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

例如:

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

【讨论】:

  • 同样,您可以使用np.arctan2(y,x),但 x 和 y 应该具有相同的形状,这不是您的情况。
  • 附带说明,在您的情况下,r 等于欧西德距离,因此您可以使用:from scipy.spatial.distance import euclidean;euclidean(x,y)
  • 是的,我必须使用 np.arctan2。我的阵列没问题,形状都一样。
  • 注意:我不需要np.square**2 工作正常。
猜你喜欢
  • 2011-02-15
  • 2018-07-13
  • 2011-04-28
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
相关资源
最近更新 更多