【发布时间】:2021-05-18 00:51:31
【问题描述】:
我有以下带有自定义函数的代码:
import numpy as np
from scipy.integrate import quad
from scipy.special import binom
from scipy.stats import norm
import math as mt
ranks = np.array([[8, 5, 3, 7, 6, 2, 1, 4],
[8, 5, 3, 7, 6, 2, 1, 4]])
def E(r, n):
print(r,n)
def f(x):
F = Phi(x)
return x*(1-F)**(r-1)*F**(n-r)*phi(x)
return -r*binom(n, r)*quad(f, -inf, inf)[0]
我想对数组ranks的每一行应用函数E。
我尝试了np.apply_along_axis,但我遇到的问题是该函数有 2 个参数:数组行中元素的单个等级 (r) 和该行的长度 (@ 987654326@).
另外,我想知道使用map 是否会更快更好,就像上面提到的问题的公认答案一样(因为速度对此很重要)。
这是我尝试过的:
result = np.apply_along_axis(E, 1, ranks)
问题:我需要提供 n 参数。此外,这可能比映射慢。
#not sure if the "*" is needed or what it does.
def E2(i):
return [*E(ranks[i], len(ranks[i]))]
it = 2 #2 rows (iterations)
indx = np.arange(it)
result = np.array(list(map(E2, indx)))
问题:每行一次需要 1 个等级。不知道如何实现。
提前致谢!
【问题讨论】:
-
如果我理解正确,n 是
len(r),因此传递该信息是多余的。它应该只是在函数内部计算。 -
apply_along_axis不是速度工具。迭代超过 2 维或更多维(3d+ 数组)时可能很方便,但它不会使迭代更快。如果使用起来不方便,那就算了。我更喜欢列表理解而不是地图,因为它的表现力。 -
@Reti43 我愿意尝试,但这意味着我需要将行的每个元素和行本身传递给该行的每个值的函数。
标签: python arrays function numpy