简体   繁体   English

python 有效地将 function 应用于多个 arrays

[英]python efficiently applying function over multiple arrays

(new to python so I apologize if this question is basic) (python 的新手,如果这个问题很基础,我深表歉意)

Say I create a function that will calculate some equation假设我创建了一个 function 来计算一些方程式

def plot_ev(accuracy,tranChance,numChoices,reward): 
     ev=(reward-numChoices)*1-np.power((1-accuracy),numChoices)*tranChance)
     return ev

accuracy, tranChance, and numChoices are each float arrays accuracy、tranChance 和 numChoices 都是浮点数 arrays

e.g. 
accuracy=np.array([.6,.7,.8])
tranChance=np.array([.6,.7,8])
numChoices=np.array([2,.3,4])

how would I run and plot plot_ev over my 3 arrays so that I end up with an output that has all combinations of elements (ideally not running 3 forloops)我将如何在我的 3 arrays 上运行和 plot plot_ev 以便我最终得到一个具有所有元素组合的 output(理想情况下不运行 3 forloops)

ideally i would have a single plot showing the output of all combinations (1st element from accuracy with all elements from transChance and numChoices, 2nd element from accuracy with all elements from transChance and numChoices and so on )理想情况下,我会有一个 plot 显示所有组合的 output(第一个元素来自 accuracy,所有元素来自 transChance 和 numChoices,第二个元素来自 accuracy,所有元素来自 transChance 和 numChoices 等等)

thanks in advance!提前致谢!

Use numpy.meshgrid to make an array of all the combinations of values of the three variables .使用numpy.meshgrid制作三个变量值的所有组合的数组

products = np.array(np.meshgrid(accuracy, tranChance, numChoices)).T.reshape(-1, 3)

Then transpose this again and extract three longer arrays with the values of the three variables in every combination:然后再次转置它并提取三个更长的 arrays 以及每个组合中三个变量的值:

accuracy_, tranChance_, numChoices_ = products.T

Your function contains only operations that can be carried out on numpy arrays, so you can then simply feed these arrays as parameters into the function:您的 function 仅包含可以在 numpy arrays 上执行的操作,因此您可以简单地将这些 arrays 作为参数输入 function:

reward = ??  # you need to set the reward value
results = plot_ev(accuracy_, tranChance_, numChoices_, reward)

Alternatively consider using a pandas dataframe which will provide clearer labeling of the columns.或者考虑使用 pandas dataframe,这将提供更清晰的列标签。

import pandas as pd
df = pd.DataFrame(products, columns=["accuracy", "tranChance", "numChoices"])
df["ev"] = plot_ev(df["accuracy"], df["tranChance"], df["numChoices"], reward)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM