[英]Iterate 2D arrays and assignment to variables of function in python
I am new to Python. I have a 2D array (10,4) and need to iterate array elements by assigning four values of each row to four variables of function (x1, x2, x3, x4), and return function output. Please have a look at my code and give me suitable suggestions.我是Python的新手。我有一个二维数组(10,4),需要通过将每一行的四个值分配给function(x1,x2,x3,x4)的四个变量来迭代数组元素,并返回function output。请看看我的代码并给我合适的建议。 Thanks
谢谢
import pandas as pd
import numpy as np
nv = 4
lb = [0, 0, 0, 0]
ub = [20, 17, 17, 15]
n = 10
def random_population(nv,n,lb,ub):
pop = np.zeros((n, nv))
for i in range(n):
pop[i,:] = np.random.uniform(lb,ub)
return pop
population = random_population(nv, n, lb, ub)
i = 0 #row number
j = 0 # col number
rows = population.shape[0]
cols = population.shape[1]
x1 = population[i][j]
x2 = population[i][j+1]
x3 = population[i][j+2]
x4 = population[i][j+3]
def test(x1, x2, x3, x4):
##Assignment statement
y = x1+x2+x3+x4
return y
test(x1, x2, x3, x4)
You can use the Python star expression to pass an array as a list of arguments to your test function.您可以使用 Python 星号表达式将一个数组作为 arguments 的列表传递给您的测试 function。
test(*population[i])
// instead of
x1 = population[i][j]
x2 = population[i][j+1]
x3 = population[i][j+2]
x4 = population[i][j+3]
test(x1, x2, x3, x4)
Turns out you can just give your function numpy arrays and since addition between them is defined as element-wise addition it does what you want.结果你可以只给你的 function numpy arrays 因为它们之间的加法被定义为逐元素加法,所以它会做你想要的。 So you first extract columns out of your array like this
所以你首先像这样从数组中提取列
population[:,0], population[:,1], ...
then然后
test(population[:,0],population[:,1],population[:,2],population[:,3])
gives you an array and the first value agrees with给你一个数组,第一个值与
test(x1, x2, x3, x4).
The question is not clear, but if I got the goal correctly and the author needs just iterating based on the title ( instead of vectorizing as mentioned by Michael Szczesny in the comments ), the following loop will put each row of the population array into the test function :问题不清楚,但如果我的目标正确并且作者只需要根据标题进行迭代(而不是像Michael Szczesny在评论中提到的那样进行矢量化),则以下循环会将population 数组的每一行放入测试 function :
for row in population:
x1, x2, x3, x4 = row
test(x1, x2, x3, x4)
or或者
for row in population:
test(*row)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.