我有一个依赖于5个变量的函数。我还有一组这些变量的数据。
我的问题是如何为所有数据运行该功能?我希望得到一个矢量。
def My_funct(a, b, c, d, e):
#do something
我的变量集是:
a = [a1, a2, a3, a4....etc]
b = [b1, b2, b3, b4....etc]
c = [c1, c2, c3, c4....etc]
d = [d1, d2, d3, d4....etc]
e = [e1, e2, e3, e4....etc]
任何有用的将不胜感激。
答案 0 :(得分:0)
The most efficient approach would be to use numpy
arrays and to make sure your function is as vectorized as possible.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = np.array([9, 10, 11, 12])
d = np.array([13, 14, 15, 16])
e = np.array([17, 18, 19, 20])
def magic(a, b, c, d, e):
return a + b + c + d + e
print(magic(a, b, c, d, e))
# [45 50 55 60]
This can even be generalized for an arbitrary number of arrays:
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
c = np.array([9, 10, 11, 12])
d = np.array([13, 14, 15, 16])
e = np.array([17, 18, 19, 20])
def magic(*arrays):
return sum(arrays)
print(magic(a, b, c, d, e))
# [45 50 55 60]
print(magic(a, b))
# [ 6 8 10 12]
答案 1 :(得分:0)
我在矩阵的每一行(包含所有数据)上做了一个lambda函数。
#df = matrix with data
result = df.apply(lambda x: my_funct(x['a'], x['b'], x['c'], x['d'], x['e']), axis=1)
希望这可能有用。