2. Numpy operations

There are a few NumPy operations that you should know. We are going to learn basic mathematical operations in this class.

import numpy as np

round()

The round function is used to round the numbers in an array.

Input:

In [8]
weight = [100.56, 300.76, 500.897, 200.453]
arr = np.array(weight)
arr = np.round(weight, 1)
arr

Output:

array([100.6, 300.8, 500.9, 200.5])

sum()

The sum function adds all the values in an array.

Input:

In [9]
np.sum(arr)

Output:

max()

max finds the highest value.

Input:

Output:

min()

min finds the lowest value.

Input:

Output:

mean

mean is also called average (arithmetical average).

Input:

Output:

arange()

arange gives us an array in a range. It has 3 parameters:

  • start: where to start your range. Default value is 0.

  • stop: where to stop. No default value.

  • step: number of steps. Default value is 1.

Examples:

Input:

Output:

Input:

Output:

Input:

Output:

Print all even numbers from 1 to 100:

Input:

Output:

random

NumPy's random module provides functions to generate random values:

  • random.randint() - random integers.

  • random.uniform() - random floats.

  • random.choice() - random values chosen from given choices.

random.randint()

Generates random integers.

Parameters:

  • low: lowest value

  • high: highest value

  • size: number of values

Input:

Output:

random.uniform()

Generates random float values.

Parameters:

  • low: lowest value

  • high: highest value

  • size: number of values

Input:

Output:

random.choice()

Chooses random values from given choices.

Input:

Output:

Input:

Output:

Example: Create a dictionary using random values

Input:

Output (example):

Assignments

  1. Create a list of Maths scores.

  2. Convert the list into an array.

  3. Give the Total Score, Maximum Score, Minimum and Mean (Average) Score.

  4. Create a NumPy array of a table of 5 (e.g., multiples of 5 or a 5x5 table — interpret as needed).

  5. Generate a reverse array from 10 to 1.

  6. Generate an array of 20 random integers.

  7. Generate an array of 20 random floats.

  8. Create a dictionary of 5 people with random height, weight, age, hair color.

(You can implement these using the NumPy functions shown above.)