【Python】一文学会使用 Numpy 库(数组)
创建 NumPy 数组
创建一个数组:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
2. 零或一的数组
创建一个填充零的数组:
zeros = np.zeros((3, 3)) # A 3x3 array of zeros
ones = np.ones((2, 4)) # A 2x4 array of ones
3. 创建一个数字范围
创建一个数字序列:
range_array = np.arange(10, 50, 5) # From 10 to 50, step by 5
4. 创建线性间隔数组
创建一系列值,这些值在两个界限之间均匀分布:
linear_spaced = np.linspace(0, 1, 5) # 5 values from 0 to 1
5. 重新塑形数组
将数组形状转换,改变其维度:
reshaped = np.arange(9).reshape(3, 3) # Reshape a 1D array into a 3x3 2D array
6. 基本数组操作
对数组执行元素操作:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
sum = a + b # Element-wise addition
difference = b - a # Element-wise subtraction
product = a * b # Element-wise multiplication
7. 矩阵乘法
基本点积运算:
result = np.dot(a.reshape(1, 3), b.reshape(3, 1)) # Dot product of a and b
8. 访问数组元素
访问数组元素的有用语法:
element = a[2] # Retrieve the third element of array 'a'
row = reshaped[1, :] # Retrieve the second row of 'reshaped'
9. 布尔索引
通过条件筛选器过滤数组元素:
filtered = a[a > 2] # Elements of 'a' greater than 2
10. 聚合与统计
统计操作在 NumPy 数组上:
mean = np.mean(a)
maximum = np.max(a)
sum = np.sum(a)