Bạn đang xem thử công khai
Đăng nhập để lưu tiến độ, làm bài tập, thảo luận và nhận phản hồi.
After this lesson you will be able to: create and access NumPy arrays, compute on whole arrays without loops, and understand why arrays are more compact and faster than lists.
Python lists are very flexible but slow with large amounts of data, because every element is a separate object. A NumPy array (ndarray) stores numbers of the same type contiguously in memory, so computations are fast and the syntax is concise. Pandas is built on NumPy: understanding arrays first makes DataFrames much easier.
import numpy as np
a = np.array([1, 2, 3])
print(np.arange(0, 10, 2)) # [0 2 4 6 8] (like range: stops before 10)
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ] (5 evenly spaced points, including both endpoints)
print(np.zeros((2, 3))) # array of all zeros with 2 rows x 3 columns
print(np.ones(3)) # [1. 1. 1.]
Every array has three frequently used attributes: shape (the size of each dimension), ndim (the number of dimensions) and dtype (the common data type).
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.shape) # (2, 3)
print(m.ndim) # 2
print(np.array([1, 2.5]).dtype) # float64 (one float makes the whole array float)
print(np.arange(12).reshape(3, 4).shape) # (3, 4)
Indices start at 0. For a 2-dimensional array, write m[row, column]; the : symbol means "all".
print(m[1, 2]) # 6 (row 1, column 2)
print(m[:, 1]) # [2 5] (all of column 1)
print(m[0]) # [1 2 3] (all of row 0)
Slicing a[i:j] stops right before j, just like with lists.
Operations apply to each element without needing for:
a = np.array([1, 2, 3])
print(a * 2) # [2 4 6]
print(a + 10) # [11 12 13] ← broadcasting: the number 10 is "stretched" to match the array
print([1, 2, 3] * 2) # [1, 2, 3, 1, 2, 3] ← with a list, * repeats the list, NOT element-wise multiplication
Broadcasting lets you add or multiply an array by a number (or by a smaller array with a compatible shape) without writing a loop.
b = np.array([5, 1, 4, 2, 3])
print(b > 2) # [ True False True False True]
print(b[b > 2]) # [5 4 3] (keeps the elements satisfying the condition)
axis parameterprint(m.sum()) # 21
print(m.mean()) # 3.5
print(m.sum(axis=0)) # [5 7 9] (sum down the rows → one sum per column)
print(m.sum(axis=1)) # [ 6 15] (sum across the columns → one sum per row)
Memory tip: axis=0 means "collapse the rows" (leaving one value for each column); axis=1 means "collapse the columns".
* on lists with * on NumPy arrays (see section 4).axis=0 with axis=1.shape, ndim and dtype describe an array.a[a > 2].axis=0 gives a result per column, axis=1 gives a result per row.McKinney, W. (2022). Python for Data Analysis: Data Wrangling with Pandas, NumPy, and Jupyter (3rd ed.). O'Reilly Media.