NumPy
Numerical Python
Python's numerical computing library. Provides multidimensional arrays (ndarray) and vector operations. The foundation of data science.
Numerical Python
Python's numerical computing library. Provides multidimensional arrays (ndarray) and vector operations. The foundation of data science.
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.
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)
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."
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
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
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?
If this page has any errors or you would like to add something, please let us know!