python 在多个数组上高效应用函数
python efficiently applying function over multiple arrays
(python 的新手,如果这个问题很基础,我深表歉意)
假设我创建了一个函数来计算一些方程
def plot_ev(accuracy,tranChance,numChoices,reward):
ev=(reward-numChoices)*1-np.power((1-accuracy),numChoices)*tranChance)
return ev
accuracy、tranChance 和 numChoices 都是浮点数组
e.g.
accuracy=np.array([.6,.7,.8])
tranChance=np.array([.6,.7,8])
numChoices=np.array([2,.3,4])
我将如何 运行 并在我的 3 个数组上绘制 plot_ev 以便我最终得到包含所有元素组合的输出(理想情况下不是 运行ning 3 forloops)
理想情况下,我会用一个图显示所有组合的输出(第一个元素来自 accuracy,所有元素来自 transChance 和 numChoices,第二个元素来自 accuracy,所有元素来自 transChance 和 numChoices 等等)
提前致谢!
使用numpy.meshgrid
to make an array of all the combinations of values of the three variables.
products = np.array(np.meshgrid(accuracy, tranChance, numChoices)).T.reshape(-1, 3)
然后再次转置并提取三个更长的数组,其中包含每个组合中三个变量的值:
accuracy_, tranChance_, numChoices_ = products.T
您的函数只包含可以在 numpy 数组上执行的操作,因此您可以简单地将这些数组作为参数提供给函数:
reward = ?? # you need to set the reward value
results = plot_ev(accuracy_, tranChance_, numChoices_, reward)
或者考虑使用 pandas 数据框,这将提供更清晰的列标签。
import pandas as pd
df = pd.DataFrame(products, columns=["accuracy", "tranChance", "numChoices"])
df["ev"] = plot_ev(df["accuracy"], df["tranChance"], df["numChoices"], reward)
(python 的新手,如果这个问题很基础,我深表歉意)
假设我创建了一个函数来计算一些方程
def plot_ev(accuracy,tranChance,numChoices,reward):
ev=(reward-numChoices)*1-np.power((1-accuracy),numChoices)*tranChance)
return ev
accuracy、tranChance 和 numChoices 都是浮点数组
e.g.
accuracy=np.array([.6,.7,.8])
tranChance=np.array([.6,.7,8])
numChoices=np.array([2,.3,4])
我将如何 运行 并在我的 3 个数组上绘制 plot_ev 以便我最终得到包含所有元素组合的输出(理想情况下不是 运行ning 3 forloops)
理想情况下,我会用一个图显示所有组合的输出(第一个元素来自 accuracy,所有元素来自 transChance 和 numChoices,第二个元素来自 accuracy,所有元素来自 transChance 和 numChoices 等等)
提前致谢!
使用numpy.meshgrid
to make an array of all the combinations of values of the three variables.
products = np.array(np.meshgrid(accuracy, tranChance, numChoices)).T.reshape(-1, 3)
然后再次转置并提取三个更长的数组,其中包含每个组合中三个变量的值:
accuracy_, tranChance_, numChoices_ = products.T
您的函数只包含可以在 numpy 数组上执行的操作,因此您可以简单地将这些数组作为参数提供给函数:
reward = ?? # you need to set the reward value
results = plot_ev(accuracy_, tranChance_, numChoices_, reward)
或者考虑使用 pandas 数据框,这将提供更清晰的列标签。
import pandas as pd
df = pd.DataFrame(products, columns=["accuracy", "tranChance", "numChoices"])
df["ev"] = plot_ev(df["accuracy"], df["tranChance"], df["numChoices"], reward)