Python / Data Science Essentials Interview Questions
What are the main ways to create NumPy arrays?
Knowing the idiomatic array-creation functions is a baseline NumPy skill. Each function is designed for a specific situation and picking the right one keeps code readable and avoids unnecessary copies.
import numpy as np # From Python sequences a = np.array([1, 2, 3, 4]) # 1-D, dtype inferred (int64) b = np.array([[1, 2], [3, 4]], dtype=np.float32) # 2-D, explicit dtype # Pre-filled arrays np.zeros((3, 4)) # 3Ã4 array of 0.0 np.ones((2, 2)) # 2Ã2 array of 1.0 np.full((3, 3), 7) # 3Ã3 array filled with 7 np.eye(4) # 4Ã4 identity matrix # Ranges np.arange(0, 10, 2) # [0 2 4 6 8] â like range() but returns ndarray np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.] â N evenly spaced points # Random arrays (use default_rng for reproducibility) rng = np.random.default_rng(seed=42) rng.random((3, 3)) # uniform [0, 1) rng.standard_normal(1000) # standard normal distribution rng.integers(0, 100, size=10) # random ints in [0, 100) # From existing data without copying np.asarray([1.0, 2.0, 3.0]) # no copy if already array-like and matching dtype np.frombuffer(b'\x01\x02\x03', dtype=np.uint8) # from raw bytes
np.linspace is preferred over np.arange for floating-point ranges because arange with a float step can produce unexpected element counts due to floating-point rounding. linspace guarantees exactly N points.
More Related questions...