Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Arrays with NumPy

NumPy

This notebook introduces NumPy (Numerical Python), the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.

Installation and Import

To use NumPy, we first need to import it. The community standard is to import it as np.

Output
NumPy version: 2.4.0

Creating Arrays

Unlike Python lists, NumPy arrays are homogenous (all elements must be of the same type). This allows them to be much faster and more memory efficient.

Creating arrays from lists

We can create an array using np.array().

Output
[12 15 14 10 18]
<class 'numpy.ndarray'>

Built-in array generators

NumPy offers functions to generate arrays automatically, which is useful for creating datasets for testing.

  • np.arange(start, stop, step): Like Python’s range but returns an array.

  • np.linspace(start, stop, num): Creates num evenly spaced values between start and stop.

  • np.zeros((rows, cols)): Creates an array filled with zeros.

  • np.ones((rows, cols)): Creates an array filled with ones.

Output
Regions (arange): [0 1 2 3 4 5 6 7 8 9]
Percentages (linspace): [  0.  25.  50.  75. 100.]

Zero Matrix:
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Array Attributes

Inspect the structure of your data using these attributes:

  • ndim: Number of dimensions (axes).

  • shape: The dimensions of the array (rows, columns).

  • size: Total number of elements.

  • dtype: The data type of the elements (e.g., int64, float64).

Output
Dimensions (ndim): 2
Shape (rows, cols): (2, 3)
Total Elements (size): 6
Data Type (dtype): int64

Practice Exercises

The following exercises are designed to test your understanding of NumPy basics.

Creating a Household Income Array

Task: Create a NumPy array from a list of household incomes provided below. Print the array and its data type.

Source
Income Array: [25000 32000 18000 45000 29000]
Data Type: int64

Generating ID Codes

Task: Use np.arange to generate an array of ID codes from 100 to 110 (inclusive of 100, exclusive of 110).

Source
ID Codes: [100 101 102 103 104 105 106 107 108 109]

Placeholder Data

Task: Create a 1D array of 5 zeros using np.zeros to serve as a placeholder for incoming census data.

Source
Placeholders: [0. 0. 0. 0. 0.]

Reshaping Data

Task: Create a 1D array containing 12 data points representing monthly inflation rates. Reshape this array into a 2D array with 4 rows (Quarters) and 3 columns (Months).

Source
Quarterly View:
 [[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

Broadcasting Operations

Task: You have an array of population counts. You to project a 10% growth for next year. Multiply the entire array by 1.10.

Source
Projected Population: [1100. 2750. 3300. 4620.]

Statistical Calculations

Task: Given a list of age data, calculate the mean (average) age and the standard deviation.

Source
Average Age: 37.14
Standard Deviation: 14.24

Filtering and Sorting

Task 1: Filter an array of city populations to find only those cities with a population greater than 1000000.

Source
[{'name': 'Manila', 'pop2025': 1600000}
 {'name': 'Quezon City', 'pop2025': 2900000}
 {'name': 'Davao City', 'pop2025': 1832753}]

Task 2: What are the top 5 cities based on population? Return only the names of the cities.

Source
The top 5 cities in terms of population are
Quezon City
Davao City
Manila
Zamboanga City
Cebu City