1

Im trying to iterate over a nested (numpy) array using np.nditer().

Converted a nested list of ints to a nested numpy array.

from numpy import mean, array, nditer

nested_list = [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]

np_array = []
for i in nested_list:
    a = array(nested_list)
np_array.append(a)

The above works, yielding;

[array([[1,2,3],
       [2,3,4],
       [3,4,5],
       [4,5,6]])]

I want to calculate the mean of each nested sub-list... I have tried this but it's not working correctly.

np_mean = []
c = 0
for i in nditer(np_array):
    m = mean(i)
    np_mean_rep.append(m)
    c += 1
print np_mean_rep

...this kinda flattens the nested array so i doesn't point to each nested sub-list but instead to each value. How would I use nditer in a way so this would work? Any pointer would be greatly appreciated!

2
  • Hmm.. ok.I just googled iterating over numpy arrays and found nditer. However, when trying this: np_array = [] for i in nested_array: b = array(nested_list).mean(axis=1) print np_array.append(b) I get None Commented May 10, 2013 at 14:44
  • but if the array is nested (as above), then i should point to each sub-list, right? and then calculate the mean for each and append it to the np_array list? What does axis=1 point to? Im a beginner in both python and numpy. Commented May 10, 2013 at 14:54

1 Answer 1

3

[migrated from comments]

I think you're making things much harder than they need to be. Arrays have a .mean() method, and you don't have to build objects row by row. You can do it all at once.

>>> import numpy as np
>>> nested_list = [[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
>>> np.array(nested_list)
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])
>>> np.array(nested_list).mean(axis=1)
array([ 2.,  3.,  4.,  5.])
>>> np.array(nested_list).mean(axis=0)
array([ 2.5,  3.5,  4.5])

The axis parameter specifies which dimension of the array we want to take the average over.

In general -- though not always -- if you find yourself writing for loops with numpy, you're doing something wrong. A basic rule when working with numpy is to try to vectorize everything (i.e. write your code in terms of operations that can be performed on the whole array at once), which means the hard work is done in the fast C library and not at the slow Python level.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.