索引与切片
数据分析离不开统计:求和、均值、最大最小、标准差、百分位数。NumPy 提供全套,还支持按轴(axis)计算。
聚合函数
sum、mean、median、min、max、std、var、argmax、argmin、percentile、cumsum。
axis 参数
axis=0 沿行方向(按列算),axis=1 沿列方向(按行算)。对二维数组做统计时必用。
代码示例
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("全部求和:", arr.sum()) # 21
print("每列求和:", arr.sum(axis=0)) # [5 7 9]
print("每行求和:", arr.sum(axis=1)) # [6 15]
data = np.array([10, 20, 30, 40, 50, 60])
print("均值:", data.mean())
print("中位数:", np.median(data))
print("标准差:", data.std())
print("最大位置:", data.argmax()) # 5
print("90 分位:", np.percentile(data, 90))
print("累计和:", np.cumsum(data)) # [10 30 60 ...]
📚 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 包名 | 安装第三方包(命令行) |