Reputation: 3512
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!
Upvotes: 1
Views: 2184
Reputation: 352959
[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.
Upvotes: 3