Fabrice Schlegel Fabrice Schlegel - 5 months ago 22
Python Question

Iterate through a bunch of numpy arrays stored as different variables

I would like to iterate through a series of numpy arrays whose variable names look like

numpy_array_001, numpy_array_002, ... numpy_array_N

To add them up, I'm looking for something like:

sum += "numpy_array_"+str(number)

The issue with the above is that
becomes a string and is no longer an array, so that doesn't work.

How can I rewrite this last line to add the arrays together?

The expected outcome is

sum = numpy_array_001 + numpy_array_002+ ... + numpy_array_N

for any N

Answer Source

I'm sorry, I think you'll have to use the eval function for this.

Here's a simple example in which I have three variables (x1, x2, x3) and I add them up:

x1 = 1
x2 = 2
x3 = 3

# Make an string containing the expression to evaluate
for i in range(3):
  expr = expr + 'x' + str(i+1) + ' + '
expr = expr[0:-3] # remove the last ' + '

# Show the expression, and evaluate it

You can adapt this to do sum += instead. So something like:

for i in range(N):  
    eval('sum += numpy_array_' + '{:03}'.format(i+1)')

But really, if you have any control over this, you should design your program such that it doesn't store a bunch of arrays in separate variables like that. That's just making life difficult for yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download