πŸ“Š Data Engineering

NumPy

Numerical Python

Python's numerical computing library. Provides multidimensional arrays (ndarray) and vector operations. The foundation of data science.

πŸ“– Detailed Explanation

NumPy (Numerical Python) is a Python numerical computing library created in 2005 by Travis Oliphant by unifying Numeric and Numarray. The ndarray (N-dimensional array), implemented in C, provides vector operations 50-100 times faster than Python lists, and is the foundation of the entire data science ecosystem.

Broadcasting is a core feature of NumPy that automatically handles operations between arrays of different shapes. When a (3, 4) array and a (4,) array are added, the latter is automatically expanded along the row direction before the operation. Vectorized code can be written without explicit loops, improving both performance and readability.

Its main features include linear algebra (np.linalg), Fourier transforms (np.fft), random number generation (np.random), and statistical functions (mean, std, percentile). Memory-efficient data types such as float32, float64, and int64 are specified with dtype, and array shapes are manipulated with reshape, transpose, and concatenate.

Pandas DataFrames, TensorFlow/PyTorch tensors, and scikit-learn inputs are all compatible with NumPy arrays. When GPU acceleration is needed, CuPy (NVIDIA CUDA) and JAX (Google TPU) use the NumPy API as is.

πŸ’» Code Example

import numpy as np

# λ°°μ—΄ 생성
arr = np.array([1, 2, 3, 4, 5])
matrix = np.arange(12).reshape(3, 4)  # 0~11을 3x4 ν–‰λ ¬λ‘œ
zeros = np.zeros((2, 3), dtype=np.float32)
ones = np.ones((3, 3))
identity = np.eye(4)  # 4x4 λ‹¨μœ„ν–‰λ ¬

print(f"Shape: {matrix.shape}, Dtype: {matrix.dtype}")
# Shape: (3, 4), Dtype: int64

# λΈŒλ‘œλ“œμΊμŠ€νŒ… 예제
a = np.array([[1], [2], [3]])  # (3, 1)
b = np.array([10, 20, 30, 40])  # (4,)
result = a + b  # (3, 4) - μžλ™ ν™•μž₯
print(result)
# [[11 21 31 41]
#  [12 22 32 42]
#  [13 23 33 43]]

# 벑터화 μ—°μ‚° (반볡문 λŒ€μ‹ )
data = np.random.randn(1000000)
# 느림: [x**2 for x in data]
squared = data ** 2  # 빠름: 벑터화 μ—°μ‚°

# 인덱싱과 μŠ¬λΌμ΄μ‹±
arr = np.arange(10)
print(arr[2:7:2])      # [2 4 6] - start:stop:step
print(arr[arr > 5])    # [6 7 8 9] - λΆˆλ¦¬μ–Έ 인덱싱

# κ³ κΈ‰ 인덱싱 (Fancy Indexing)
indices = np.array([1, 3, 5])
print(arr[indices])    # [1 3 5]

# μ„ ν˜•λŒ€μˆ˜
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

print(A @ B)              # ν–‰λ ¬ κ³±μ…ˆ
print(np.linalg.det(A))   # 행렬식: -2.0
print(np.linalg.inv(A))   # μ—­ν–‰λ ¬
eigenvalues, eigenvectors = np.linalg.eig(A)

# 톡계 ν•¨μˆ˜
data = np.random.normal(100, 15, size=1000)
print(f"평균: {np.mean(data):.2f}")
print(f"ν‘œμ€€νŽΈμ°¨: {np.std(data):.2f}")
print(f"쀑앙값: {np.median(data):.2f}")
print(f"95 퍼센타일: {np.percentile(data, 95):.2f}")

# μΆ•(axis) 기반 μ—°μ‚°
matrix = np.random.randint(0, 10, size=(3, 4))
print(f"열별 합계: {matrix.sum(axis=0)}")  # (4,)
print(f"행별 합계: {matrix.sum(axis=1)}")  # (3,)

# λ°°μ—΄ κ²°ν•©
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6]])
vertical = np.vstack([arr1, arr2])    # (3, 2)
horizontal = np.hstack([arr1, arr1])  # (2, 4)

πŸ—£οΈ Examples of Practical Conversations

Senior: "This is feature preprocessing logic, and running it through a for loop over 1 million rows takes 5 minutes. Vectorizing it with NumPy can bring it down to under 1 second."

Junior: "What is broadcasting?"

Senior: "It automatically aligns dimensions when operating on arrays with different shapes. To subtract the mean of each column from a (1000, 10) array, you can just do data - data.mean(axis=0)."

Interviewer: "Do you have experience with NumPy performance optimization?"

Candidate: "I replaced loops with vectorized operations and cut memory in half by reducing dtype from float64 to float32. I solved out-of-memory problems by memory-mapping large arrays to disk with np.memmap, and JIT-compiled the compute-intensive parts with Numba's @jit decorator."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "If you leave out arr.copy(), a view is returned and the original can be modified. If you're going to modify the slicing result, call copy() explicitly."

Developer: "Ah, so that's why the original data changed. I'll fix it right away."

⚠️ Cautions

πŸ”₯ Real-World Incidents

ML Startup 2022

Converting float64β†’float32 caused precision loss and a sharp drop in model performance

Cause: dtype was changed to float32 indiscriminately to optimize memory, causing precision loss in a financial model

Impact: Trading prediction model accuracy dropped by 15%, and actual losses occurred

Resolution: Kept float64 for critical columns and used float32 only for less important features

Lesson: Before changing dtype, review domain-specific precision requirements and test the impact with a validation dataset

General Case Common

Original data corrupted because slicing returned a view

Cause: Unaware that the arr[::2] slice returns a view, so modifying it also changed the original

Impact: Training data was altered, requiring model retraining, and debugging took two days

Resolution: Made an explicit copy with .copy() before modifying

Lesson: NumPy slicing returns a view; always consider .copy() before modifying

πŸ“ Comprehension Quiz

Q1. What is broadcasting in NumPy?

Q2. After arr = np.arange(10); b = arr[2:5], what happens if you set b[0] = 99?

Q3. Which is a correct way to optimize NumPy performance?

πŸ“š Learn More

πŸ’¬ Questions & Contributions

If this page has any errors or you would like to add something, please let us know!