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. 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)
CodePudding user response:
You can use the Python star expression to pass an array as a list of arguments to your test 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)
CodePudding user response:
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. 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).