Python 实用速成教程(科研导向,完整版)
面向已经掌握其他编程语言的程序员,帮助快速掌握 Python 的科研常用技能。强调实用性、完整性和清晰表达,避免炫技写法。
1. 环境准备
推荐方式:使用虚拟环境管理依赖。
1 2 3 4 5 6 7
| python3 -m venv venv source venv/bin/activate venv\Scripts\activate
pip install numpy scipy pandas matplotlib jupyter
|
启动 Jupyter Notebook:
2. 基本语法
2.1 变量与数据类型
1 2 3 4
| x = 10 pi = 3.14 name = "Alan" flag = True
|
2.2 条件语句
1 2 3 4 5 6
| if x > 0: print("正数") elif x == 0: print("零") else: print("负数")
|
2.3 循环
1 2 3 4 5 6 7
| for i in range(5): print(i)
count = 0 while count < 3: print("循环", count) count += 1
|
3. 常用数据结构
3.1 列表
1 2 3
| nums = [1, 2, 3] nums.append(4) print(nums[0])
|
3.2 字典
1 2 3 4 5
| person = {"name": "Alan", "age": 25} print(person["name"])
print(person.get("gender", "未知"))
|
3.3 集合
1 2 3
| s = {1, 2, 3} s.add(2) print(s)
|
4. 函数与模块
1 2 3 4
| def greet(name): return f"Hello, {name}"
print(greet("Alan"))
|
导入模块:
1 2
| import math print(math.sqrt(16))
|
5. 文件与数据读写
5.1 文本文件
1 2 3
| with open("data.txt", "r") as f: for line in f: print(line.strip())
|
5.2 CSV 文件
1 2 3 4 5 6
| import csv
with open("data.csv", newline="") as f: reader = csv.reader(f) for row in reader: print(row)
|
5.3 JSON 文件
1 2 3 4 5
| import json
with open("config.json") as f: data = json.load(f) print(data["param"])
|
6. NumPy 基础
6.1 创建数组
1 2 3 4
| import numpy as np
arr = np.array([1, 2, 3, 4]) print(arr)
|
6.2 数值运算
1 2 3
| print(arr + 10) print(arr.mean()) print(arr.max())
|
6.3 矩阵运算
1 2 3 4 5
| A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]])
print(A + B) print(A @ B)
|
7. pandas 数据分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import pandas as pd
df = pd.read_csv("data.csv")
print(df.head())
print(df.describe())
print(df[df["value"] > 10])
print(df.groupby("group")["value"].mean())
|
8. Matplotlib 绘图
1 2 3 4 5 6 7 8 9 10 11 12
| import matplotlib.pyplot as plt import numpy as np
x = np.linspace(0, 10, 100) y = np.sin(x)
plt.plot(x, y, label="sin(x)") plt.xlabel("x") plt.ylabel("sin(x)") plt.title("正弦函数") plt.legend() plt.show()
|
9. SciPy 常用功能
9.1 优化
1 2 3 4
| from scipy.optimize import minimize
res = minimize(lambda x: (x-3)**2, x0=0) print(res.x)
|
9.2 统计检验
1 2 3 4
| from scipy import stats
t, p = stats.ttest_ind([1,2,3], [1.1,2.1,3.1]) print("t=", t, "p=", p)
|
10. 并行与性能
10.1 多进程
1 2 3 4 5 6 7 8
| from multiprocessing import Pool
def square(x): return x*x
with Pool(4) as p: results = p.map(square, range(10)) print(results)
|
10.2 向量化替代循环
1 2 3 4 5
| out = [np.sin(v) for v in arr]
out = np.sin(arr)
|
11. 实用技巧与常见陷阱
- 使用
f"..." 进行格式化输出。
- 文件操作时总用
with open,避免忘记关闭。
- 默认参数不要用可变对象:
1 2 3 4 5
| def f(x, lst=None): if lst is None: lst = [] lst.append(x) return lst
|
12. 实践案例:科研数据分析流程
步骤:读取 → 清洗 → 分析 → 可视化 → 保存结果
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
| import pandas as pd import matplotlib.pyplot as plt
df = pd.read_csv("experiment.csv")
df = df.dropna()
print(df.describe())
summary = df.groupby("group")["value"].mean() print(summary)
summary.plot(kind="bar") plt.xlabel("Group") plt.ylabel("Mean Value") plt.title("实验结果对比") plt.show()
summary.to_csv("summary.csv")
|
13. 推荐资源
总结
- Python 语法简单,重点是熟悉科学计算库。
- 科研最常用的工具链:NumPy + pandas + Matplotlib + SciPy。
- 建议从实际任务出发,边做边学。