Home > OS >  Numpy to return average of 3D matrix
Numpy to return average of 3D matrix

Time:07-08

I have a 3D Numpy matrix named stocks that has shape (A, P, T), with A corresponding to the number of stock symbols, P corresponding to number of prices for the stock at a given point in time, and T corresponding to the time.

stocks = np.array([ [ [1,2,3],[4,5,6],[7,8,9] ], [ [10,11,12],[13,14,15],[16,17,18] ], [ [19,20,21],[22,23,24],[25,26,27] ], [ [28,29,30],[31,32,33],[34,35,36] ] ])  

I would like to return a 2D Numpy matrix of shape (P, T) where each element is the average of the stock price at a given time.

How would I do this? Thanks in advance!

CodePudding user response:

import numpy as np

# shape (A, P, T)
stocks = np.array([ [ [1,2,3],[4,5,6],[7,8,9] ], [ [10,11,12],[13,14,15],[16,17,18] ], [ [19,20,21],[22,23,24],[25,26,27] ], [ [28,29,30],[31,32,33],[34,35,36] ] ])

# this will give you the mean calculated along the first dimension
# the shape will be (P, T)
out_0 = np.mean(stocks, axis=0)

# this will be of the shape (A, T)
out_1 = np.mean(stocks, axis=1)

# this will be of the shape (A, P)
out_2 = np.mean(stocks, axis=2)
  • Related