相关疑难解决方法(0)

将python函数广播到numpy数组

假设我们有一个特别简单的功能

import scipy as sp
def func(x, y):
   return x + y
Run Code Online (Sandbox Code Playgroud)

这个功能显然适用于几种内置Python数据类型xy像串,列表,整数,浮点,数组,等等.因为我们是在阵列特别感兴趣,我们考虑两个数组:

x = sp.array([-2, -1, 0, 1, 2])
y = sp.array([-2, -1, 0, 1, 2])

xx = x[:, sp.newaxis]
yy = y[sp.newaxis, :]

>>> func(xx, yy)
Run Code Online (Sandbox Code Playgroud)

这回来了

array([[-4, -3, -2, -1,  0],
  [-3, -2, -1,  0,  1],
  [-2, -1,  0,  1,  2],
  [-1,  0,  1,  2,  3],
  [ 0,  1,  2,  3,  4]])
Run Code Online (Sandbox Code Playgroud)

正如我们所期望的那样.

现在,如果想要将数组作为以下函数的输入?

def func2(x, y):
  if x > y:
     return x …
Run Code Online (Sandbox Code Playgroud)

python numpy scipy

7
推荐指数
2
解决办法
9736
查看次数

标签 统计

numpy ×1

python ×1

scipy ×1