PY基础

三个重要的库

Numpy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import numpy as np

# 1. 创建数组
a = np.array([1, 2, 3]) # 一维
b = np.array([[1, 2], [3, 4]]) # 二维(矩阵)
c = np.zeros((3, 4)) # 全0矩阵
d = np.ones((2, 3)) # 全1矩阵
e = np.random.rand(3, 3) # 随机矩阵
f = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]

# 2. 数组属性(必须会看)
print(a.shape) # 形状,如 (3,) 或 (2, 3)
print(a.ndim) # 维度数,1或2或3
print(a.dtype) # 数据类型,如 int64, float64
print(a.size) # 元素总数

# 3. 切片(和Python列表类似但更强)
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b[0, :]) # 第一行 [1, 2, 3]
print(b[:, 1]) # 第二列 [2, 5]
print(b[0:2, 1:3]) # 行0-1,列1-2

# 4. 广播(Broadcasting)—— 非常重要
a = np.array([[1, 2, 3]]) # shape (1, 3)
b = np.array([[1], [2]]) # shape (2, 1)
print(a + b) # shape (2, 3) 自动扩展

# 5. 矩阵运算(AI中最核心)
A = np.random.rand(3, 4)
B = np.random.rand(4, 2)
C = np.dot(A, B) # 矩阵乘法 (3,4) @ (4,2) = (3,2)
C = A @ B # 等价写法
A.T # 转置

# 6. 常用操作
np.sum(a) # 所有元素求和
np.mean(a) # 平均值
np.max(a, axis=0) # 按列最大值
np.argmax(a) # 最大值的索引(分类任务预测标签常用)
np.reshape(a, (2, 3)) # 改变形状
np.concatenate([a, b]) # 拼接

Pandas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import pandas as pd

# 1. 创建和读取
df = pd.DataFrame({
"name": ["张三", "李四", "王五"],
"age": [20, 21, 22],
"score": [85, 92, 78]
})

df = pd.read_csv("data.csv") # 读CSV
df.to_csv("output.csv", index=False) # 写CSV

# 2. 查看数据
print(df.head()) # 前5行
print(df.shape) # 行数和列数
print(df.describe()) # 统计摘要
print(df.columns) # 列名

# 3. 筛选与过滤
df[df["score"] > 80] # 条件筛选
df.loc[df["age"] > 20, ["name", "score"]] # 按标签筛选
df.sort_values("score", ascending=False) # 排序

# 4. 分组聚合
df.groupby("age")["score"].mean() # 按年龄分组求平均分

# 5. 处理缺失值
df.isnull().sum() # 每列缺失数量
df.fillna(0) # 填充缺失值
df.dropna() # 删除缺失行

Matplotlib

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt

# 折线图(画loss曲线必备)
plt.plot([1, 2, 3, 4], [0.9, 0.5, 0.3, 0.1], label="loss")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.title("Training Loss")
plt.legend()
plt.savefig("loss.png")
plt.show()

# 散点图
plt.scatter(x_data, y_data, c='red')

# 直方图
plt.hist(data, bins=50)

# 多子图
fig, axes = plt.subplots(1, 2)
axes[0].plot(x, y1)
axes[1].plot(x, y2)