LimioLearn in Flow
🏆 Đấu trường
Đăng nhậpĐăng ký
← Programming for Data Science

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.

Đăng nhập
Module 2: Data Manipulation with NumPy and Pandas

NumPy Arrays

In / Lưu PDF

NumPy Arrays

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.

1. Why NumPy

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.

2. Creating arrays

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)

3. Indexing and slicing

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.

4. Whole-array computation (vectorization)

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.

5. Filtering with a condition (boolean mask)

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)

6. Aggregate functions and the axis parameter

print(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".

Common mistakes

  • Confusing * on lists with * on NumPy arrays (see section 4).
  • Confusing axis=0 with axis=1.
  • Thinking a slice includes the last index.

Remember

  • NumPy arrays: same type, fast, element-wise computation.
  • shape, ndim and dtype describe an array.
  • Filtering with a condition: a[a > 2].
  • axis=0 gives a result per column, axis=1 gives a result per row.

Reference

McKinney, W. (2022). Python for Data Analysis: Data Wrangling with Pandas, NumPy, and Jupyter (3rd ed.). O'Reilly Media.

NumPy Arrays

Lecture recording: creating arrays, indexing, boolean masks, broadcasting and aggregations.

Lecturer's notebook — open in Google Colab
Lecturer's notebook — download (.ipynb)