Module 2 · NumPy and SciPy · Lesson 10 of 66
NumPy arrays
The fast array type nearly every data science library is built on.
In this lesson · about 14 minutes
- Import NumPy as np
- Turn lists into arrays
- Build arrays with arange, zeros, ones, linspace and eye
NumPy is Python's library for working with numbers in bulk. Its array holds many values of one type and does math on all of them at once, much faster than a Python list. pandas, Matplotlib and scikit-learn are all built on top of it, which is why we learn it first.
Everyone imports it under the short name np. On your own computer you'd install it with pip install numpy (or conda install numpy with Anaconda). Here it's already available.
Arrays come in two everyday shapes: a vector is one row of values (1-D) and a matrix is a grid of rows and columns (2-D).
Built-in ways to make arrays
| Code | Gives |
|---|---|
np.arange(0, 10) | 0 to 9. Like range, the stop is left out. A third argument is the step: np.arange(0, 11, 2) is 0, 2, …, 10. |
np.zeros(3), np.zeros((5, 5)) | All zeros. Pass a tuple for a 2-D shape (rows, columns). |
np.ones(3), np.ones((3, 3)) | All ones |
np.linspace(0, 10, 3) | 3 evenly spaced numbers from 0 to 10, including 10: 0, 5, 10 |
np.eye(4) | A 4 × 4 identity matrix: ones on the diagonal, zeros elsewhere |
Exercise
Ten zeros
Create an array of 10 zeros.
Exercise
Ten fives
Create an array of 10 fives (as decimals, like 5.).
Exercise
The integers from 10 to 50
Create an array of the integers from 10 to 50, including 50.
Exercise
The even integers from 10 to 50
Create an array of all the even integers from 10 to 50, including 50.
Exercise
An identity matrix
Create a 3 × 3 identity matrix.
Exercise
20 points between 0 and 1
Create an array of 20 evenly spaced points from 0 to 1.
Exercises solved: 0 of 6
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.