Pau
Pau

Reputation: 93

Iterate through a list of numpy arrays

I have a list of multidimensional arrays, and need to access each of these arrays and operate on them. Mock up data:

list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
list_of_arrays
[array([[ 0.,  0.],[ 0.,  0.]]), array([[ 0.39881669,  0.65894242],[ 0.10857551,   0.53317832]]), array([[ 1.39833735,  0.1097232 ],[ 1.89622798,  1.79167888]]), array([[ 1.98242087,  0.3287465 ],[ 1.2449321 ,  2.27102359]])]

My questions are:

1- How could I iterate through list_of_arrays, so every iteration returns each of the individual arrays?
e.g. iteration 1 returns list_of_arrays[0]...last iteration returns list_of_arrays[-1]

2- How could I use the result of each iteration as input for another function?

I'm fairly new to Python. My first idea has been to define the function inside a for-loop, but I'm unclear how to implement this:

for i in list_of_array:
    def do_something():

I was wondering if anybody had a good solution for this.

Upvotes: 2

Views: 7590

Answers (2)

Hima
Hima

Reputation: 12054

You can just access each of the arrays by for loop and then can perform whatever you want

Examples

Using inbuilt functions

import numpy as np
list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
for i in list_of_arrays:
    print sum(i)

Using user defined functions

import numpy as np
def foo(i):
    #Do something here 

list_of_arrays = map(lambda x: x*np.random.rand(2,2), range(4))
for i in list_of_arrays:
    foo(i)

Plotting the data for analysis

import numpy as np
import matplotlib.pyplot as plt
list_of_arrays = map(lambda x: x*np.random.rand(2,100), range(4))
fig = plt.figure(figsize=(10,12))
j=1
for i in list_of_arrays:
    plt.subplot(2,2,j)
    j=j+1
    plt.scatter(i[0],i[1])
    plt.draw()
plt.show()

will give you this Row comparison in 2*100 matrix

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118011

You define the function elsewhere, then call it within the loop. You don't define the function over and over again within the loop.

def do_something(np_array):
    # work on the array here

for i in list_of_array:
    do_something(i)

As a working example, lets just say I call the sum function on each array

def total(np_array):
    return sum(np_array)

Now I can call it in the for loop

for i in list_of_arrays:
    print total(i)

Output

[ 0.  0.]
[ 1.13075762  0.87658186]
[ 2.34610724  0.77485066]
[ 1.08704527  2.59122417]

Upvotes: 3

Related Questions