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)
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:
for row in population:
x1, x2, x3, x4 = row
test(x1, x2, x3, x4)
or
for row in population:
test(*row)