1

I am new to python.

Here is my three dimensional array:

my_data=numpy.zeros((index1,index2,index3))

For illustration, let's say the sizes are:

index1 = 5
index2 = 4
index3 = 100

I want to compute the mean of all index3 values for a given index2 value.

I tried various options:

# Does not work
result[index1][index2] = numpy.mean(my_data[index1][index2][index3], axis=2)

# Also does not work
result = numpy.zeros((index1, index2))
result[index1][index2] = numpy.mean(my_data[index1][index2])

What am I missing?

CA_in_QC
  • 11
  • 1
  • Can you share the error that you are getting? – Kevin K. Nov 30 '18 at 21:25
  • items *= arr.shape[ax] IndexError: tuple index out of range – CA_in_QC Nov 30 '18 at 21:28
  • Indices need to be accessed between 0 and [the size of your array]-1. i.e. if you need to access the last element of an array of size 100 (such as your third index), you need to use `arr[99]`. So, in your question, try using `my_data[index1-1][index2-1][index3-1]` – Kevin K. Nov 30 '18 at 21:40

1 Answers1

2

Just use np.mean() with the axis keyword:

import numpy as np

np.random.seed(0)

data = np.random.randint(0,5,size=(3,3,3))

Yields:

[[[4 0 3]
  [3 3 1]
  [3 2 4]]

 [[0 0 4]
  [2 1 0]
  [1 1 0]]

 [[1 4 3]
  [0 3 0]
  [2 3 0]]]

Then apply:

np.mean(data,axis=1)

#Or data.mean(axis=1)

Returns:

[[3.33333333 1.66666667 2.66666667]
 [1.         0.66666667 1.33333333]
 [1.         3.33333333 1.        ]]
rahlf23
  • 8,869
  • 4
  • 24
  • 54