540 words
3 minutes
NumPy Array Creation

I. NumPy Array Creation (数组创建)
1. Basic Array Creation (基本数组创建)
1) np.array() — Create from List (从列表创建)
The np.array() function converts a Python List (列表) or Tuple (元组) into an ndarray (多维数组).
import numpy as np
# 1D Array (一维数组)a = np.array([1, 2, 3, 4, 5])print(a) # [1 2 3 4 5]print(a.dtype) # int64
# 2D Array (二维数组)b = np.array([[1, 2, 3], [4, 5, 6]])print(b)# [[1 2 3]# [4 5 6]]print(b.shape) # (2, 3)
# Specify dtype (指定数据类型)c = np.array([1, 2, 3], dtype=np.float32)print(c) # [1. 2. 3.]2) np.zeros() / np.ones() / np.full() — Constant Arrays (常量数组)
These functions create arrays filled with a Constant Value (常量值).
python
import numpy as np
# All zeros (全零数组)a = np.zeros((2, 3))print(a)# [[0. 0. 0.]# [0. 0. 0.]]
# All ones (全一数组)b = np.ones((3, 2), dtype=int)print(b)# [[1 1]# [1 1]# [1 1]]
# Fill with a specific value (填充指定值)c = np.full((2, 2), 7)print(c)# [[7 7]# [7 7]]
# Like versions: same shape as another array (与另一个数组形状相同)d = np.zeros_like(b)print(d)# [[0 0]# [0 0]]3) np.arange() / np.linspace() — Sequence Arrays (序列数组)
Use these to generate Evenly Spaced (等间隔) values.
python
import numpy as np
# arange: similar to range() but returns ndarray# arange(start, stop, step)a = np.arange(0, 10, 2)print(a) # [0 2 4 6 8]
# Float step (浮点步长)b = np.arange(0, 1, 0.3)print(b) # [0. 0.3 0.6 0.9]
# linspace: evenly spaced over an interval (等分区间)# linspace(start, stop, num)c = np.linspace(0, 1, 5)print(c) # [0. 0.25 0.5 0.75 1. ]
# logspace: logarithmically spaced (对数等间隔)d = np.logspace(0, 3, 4) # 10^0 to 10^3print(d) # [ 1. 10. 100. 1000.]4) np.eye() / np.identity() — Identity Matrix (单位矩阵)
python
import numpy as np
# Identity Matrix (单位矩阵)a = np.eye(3)print(a)# [[1. 0. 0.]# [0. 1. 0.]# [0. 0. 1.]]
# Offset diagonal (偏移对角线)b = np.eye(3, k=1)print(b)# [[0. 1. 0.]# [0. 0. 1.]# [0. 0. 0.]]5) np.empty() / np.diag() — Other Creation Methods (其他创建方式)
python
import numpy as np
# empty: uninitialized (未初始化, values are random)a = np.empty((2, 2))print(a) # random values, fast allocation
# diag: create diagonal matrix or extract diagonal (对角矩阵)b = np.diag([1, 2, 3])print(b)# [[1 0 0]# [0 2 0]# [0 0 3]]
# Extract diagonal from a matrix (提取对角线)c = np.array([[1, 2], [3, 4]])print(np.diag(c)) # [1 4] NumPy Array Creation
https://lxy-alexander.github.io/blog/posts/numpy/api/01numpy-array-creation/