科学计算实战
综合实战:用 NumPy 处理一份销售数据。手动实现归一化、标准化、统计摘要、过滤异常——这些是给机器学习做数据准备的常见步骤。
任务
模拟 1000 条销售记录 → 算统计 → 过滤异常(超过 3 倍标准差)→ 归一化到 0-1 → 按周聚合。
代码示例
import numpy as np
np.random.seed(42)
# 模拟 1000 条销售额(部分异常大值)
amounts = np.random.normal(500, 100, 1000)
amounts[::50] *= 8 # 故意造一些异常值
# 基本统计
print("均值:", amounts.mean().round(2))
print("中位数:", np.median(amounts).round(2))
print("标准差:", amounts.std().round(2))
# 异常检测:超出均值±3倍标准差
mean, std = amounts.mean(), amounts.std()
normal = amounts[(amounts > mean - 3 * std) & (amounts < mean + 3 * std)]
print(f"异常值过滤后剩 {len(normal)} 条(原 {len(amounts)} 条)")
# 归一化到 0-1
norm = (normal - normal.min()) / (normal.max() - normal.min())
print("归一化范围:", norm.min().round(3), "-", norm.max().round(3))
# 按每 100 条一组聚合
grouped = normal[:900].reshape(9, 100).sum(axis=1)
print("9 组每组总额:", grouped.round(0))
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |