Iterating over arrays to use as input to a function

  numpy, python-3.x

The code below works fine.

I am trying to change it a bit.

calculation is a functions that takes 2 arrays as input.

The code below inputs the 10 arrays of 100 elements each in groups of 2 (calculation needs 2 arrays as input) and it does this way:

arr[0],arr[1]
arr[2],arr[3]
arr[4],arr[5]
arr[6],arr[7]
att[8],arr[9]

So I get five results from calculation function because there’s 10 arrays.

I want to change this line:

result_func = [calculatation(y[i], y[i+1]) for i in range(0, n, 2)]

to iterate this way:

arr[0],arr[1]
arr[1],arr[2],
arr[2],arr[3],
arr[3],arr[4],
arr[4],arr[5],
arr[5],arr[6],
arr[6],arr[7],
arr[7],arr[8],
arr[8],arr[9],
arr[9],arr[0]

So I get 10 results

What’s the best way to do it?

# creating an array with 1000 samples
array = np.random.normal(0,1,1000)

# making the array an iterator
iter_array = iter(array)

# Creating a list of list to store 10 list of 10 elements each
n = 10
result = [[] for _ in range(n)]

# Starting the list creating
for _ in itertools.repeat(None, 100):
    for i in range(n):
        result[i].append(next(iter_array))
# Casting the lists to arrays        
y=np.array([np.array(xi) for xi in result], dtype=object)


#applying a function take takes 2 arrays as input
result_func = [calculatation(y[i], y[i+1]) for i in range(0, n, 2)]

Source: Python-3x Questions

LEAVE A COMMENT