Creating NumPy Arrays
The ndarray — NumPy's core data structure and how to create one
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
NumPy's core object is the ndarray (n-dimensional array). Unlike Python lists, NumPy arrays store elements of the same type, which makes them dramatically faster for numerical computation.
Creating arrays:
```python import numpy as np
# From a list a = np.array([1, 2, 3, 4, 5])
# Zeros and ones np.zeros(5) # [0. 0. 0. 0. 0.] np.ones((2, 3)) # 2×3 array of 1s
# Range of values np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
# Evenly spaced (linspace) np.linspace(0, 1, 5) # [0., 0.25, 0.5, 0.75, 1.]
# Random np.random.rand(3) # 3 random values in [0, 1) ```
Key attributes:
a.dtype— data type (e.g. float64, int32)a.shape— dimensions as a tuplea.ndim— number of dimensions
Examples
Array basics
shape is a tuple — (rows, cols) for 2D arrays
import numpy as np
a = np.array([10, 20, 30, 40])
print(a.dtype) # int64
print(a.shape) # (4,)
print(a.ndim) # 1
b = np.zeros((2, 3))
print(b.shape) # (2, 3)
print(b.ndim) # 2Next in NumPy
Array Shape & Reshape