Python Numpy 101: How to Calculate the Simple Average of a Numpy Array?

import numpy as np

# stock prices (3x per day)
# [morning, midday, evening]
solar_x = np.array(
[[2, 3, 4], # day 1
[2, 2, 5]]) # day 2


What is the output of this puzzle?
*Beginner Level* (solution below)

Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices.

This puzzle introduces the average function from the numpy library. When applied to a 1D numpy array, this function returns the average of the array values. When applied to a 2D numpy array, numpy simply flattens the array. The result is the average of the flattened 1D array.

In the puzzle, we have a matrix with two rows and three columns. The matrix gives the stock prices of the solar_x stock. Each row represents the prices for one day. The first column specifies the morning price, the second the midday price, and the third the evening price.

Note that numpy calculates the average as the sum over all values, divided by the number of values. The result is a float value.

Are you a master coder?
Test your skills now!

Related Video




Leave a Comment

Your email address will not be published. Required fields are marked *