Kostas Belivanis - 8 months ago 46

Python Question

I have this target array:

`[ 0.88 0.51 0.55 0.59 0.7 ]`

and this sample array:

`[[ 0.4 0.02 0.52 0.44 0.48]`

[ 0.53 0.73 0.13 0.15 0.78]

[ 0.67 0.27 0.26 0.31 0.17]

[ 0.37 0.51 0.98 0.2 0.57]]

and I would like to produce another array (say 'fns') that will calculate

- row0: the average of each column of the sample array
- row1: the average of each column +1 std deviation
- row2: the average of each column -1 std deviation
- row3: the RMSE of the average to the average for each column

anybody can suggest anything better than nested for statements?

Answer

You can avoid the nested for loops by using the axis argument available to many `numpy`

methods.

```
fns = np.empty((4,sample.shape[1]))
stdv = np.std(sample,axis=0)
fns[0,:] = np.mean(sample,axis=0)
fns[1,:] = fns[0,:] - stdv
fns[2,:] = fns[0,:] + stdv
fns[3,:] = np.sqrt(np.mean((sample - target)**2,axis=0))
```

Source (Stackoverflow)