Python for Data course menu
NumPy Arrays for Beginners: Create Arrays, dtype and shape
Learn NumPy arrays: why they are faster than Python lists, creating arrays with array, zeros, ones, arange and linspace, data types (dtype), shape and ndim, and 2D arrays.
On this page
NumPy (Numerical Python) provides the ndarray: a grid of values that all have the same type, stored together in memory. That design lets NumPy run maths on whole arrays at C speed instead of looping in Python. pandas, scikit-learn and almost every scientific Python library are built on it.
Creating an array#
import numpy as np
prices = np.array([120, 250, 80, 310])
print(prices)
print(type(prices))
print(prices.dtype, prices.shape, prices.ndim, prices.size)[120 250 80 310]
<class 'numpy.ndarray'>
int64 (4,) 1 4dtypeis the type of every element (here 64-bit integers).shapeis the size along each dimension;(4,)means one dimension with 4 items.ndimis the number of dimensions, andsizethe total number of elements.
Why not just use a list?#
Multiplying every price by 1.18 with a list needs a loop or comprehension; with an array, you write the maths directly:
import numpy as np
prices_list = [120, 250, 80, 310]
print([p * 1.18 for p in prices_list])
prices = np.array(prices_list)
print(prices * 1.18)[141.6, 295.0, 94.39999999999999, 365.79999999999995]
[141.6 295. 94.4 365.8]The array version is shorter and, on large data, many times faster, because the loop happens inside NumPy's compiled code. Note that prices_list * 2 would repeat the list, not double the numbers: lists and arrays behave differently with operators.
Data types#
All elements share one dtype. Mixing ints and floats gives floats; NumPy picks a type that can hold everything:
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1, 2.5, 3]).dtype)
print(np.array([True, False]).dtype)
print(np.array(["a", "bc"]).dtype)
ints = np.array([1.9, 2.1, -3.7]).astype(int)
print(ints)int64
float64
bool
<U2
[ 1 2 -3]astype(int) converts and truncates toward zero (1.9 becomes 1, −3.7 becomes −3); it does not round. <U2 means Unicode strings of up to 2 characters. For data analysis you mostly see int64, float64, bool and, in pandas, text and dates.
Ready-made arrays#
import numpy as np
print(np.zeros(3))
print(np.ones(4, dtype=int))
print(np.full(3, 7))
print(np.arange(0, 10, 2)) # like range: start, stop (excluded), step
print(np.linspace(0, 1, 5)) # 5 evenly spaced values, both ends included[0. 0. 0.]
[1 1 1 1]
[7 7 7]
[0 2 4 6 8]
[0. 0.25 0.5 0.75 1. ]arange is for integer steps; linspace is for "n points between a and b", which is what you want for plotting smooth curves.
Two-dimensional arrays#
A 2D array is a table of rows and columns:
import numpy as np
scores = np.array([
[72, 85, 90],
[64, 78, 88],
[95, 91, 87],
])
print(scores.shape) # (rows, columns)
print(scores.ndim)
print(scores[1]) # the second row
print(scores[1, 2]) # row 1, column 2
print(np.eye(3)) # identity matrix(3, 3)
2
[64 78 88]
88
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]Rows must all have the same length. NumPy can have any number of dimensions (images are often 3D: height, width, colour channels), but data analysis mostly uses 1D and 2D.
Common mistakes#
Practice#
Practice exercise
Create an array of the temperatures [21.5, 23.0, 19.8, 25.4, 22.1] in Celsius. Print its dtype and shape, convert it to Fahrenheit (C × 9/5 + 32) without a loop, and print the result rounded to one decimal place.
Show hint
Arithmetic on an array applies to every element. np.round(arr, 1) rounds to one decimal.
Show solution
import numpy as np
celsius = np.array([21.5, 23.0, 19.8, 25.4, 22.1])
print(celsius.dtype, celsius.shape)
fahrenheit = celsius * 9 / 5 + 32
print(np.round(fahrenheit, 1))float64 (5,)
[70.7 73.4 67.6 77.7 71.8]Key takeaway#
Finished this lesson?