1

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)
Husnain
  • 243
  • 1
  • 2
  • 5

3 Answers3

1

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)
Edward Ji
  • 745
  • 8
  • 19
0

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).
Lukas S
  • 3,212
  • 2
  • 13
  • 25
0

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)
Ali_Sh
  • 2,667
  • 3
  • 43
  • 66