Setup
On first use, read setup.md for integration guidelines. Creates ~/numpy/ to store preferences and snippets.
When to Use
User needs numerical computing in Python. Agent handles array operations, mathematical computations, linear algebra, and data manipulation with NumPy.
Architecture
Memory lives in ~/numpy/. See memory-template.md for structure.
CODEBLOCK0
Quick Reference
| Topic | File |
|---|
| Setup process | INLINECODE4 |
| Memory template |
memory-template.md |
Core Rules
1. Vectorize First
Never use Python loops for array operations. NumPy's vectorized operations are 10-100x faster.
CODEBLOCK1
2. Understand Broadcasting
Broadcasting allows operations on arrays of different shapes. Know the rules:
- - Dimensions align from the right
- Size-1 dimensions stretch to match
- Missing dimensions treated as size-1
CODEBLOCK2
3. Prefer Views Over Copies
Slicing returns views (same memory). Use
.copy() only when needed.
CODEBLOCK3
4. Use Appropriate Dtypes
Choose the smallest dtype that fits your data. Saves memory and speeds up computation.
CODEBLOCK4
5. Axis Awareness
Most functions accept
axis parameter. Know your axes:
- -
axis=0: operate along rows (down columns) - INLINECODE9 : operate along columns (across rows)
- INLINECODE10 or omit: operate on flattened array
CODEBLOCK5
6. Leverage Built-in Functions
NumPy has optimized functions for common operations. Don't reinvent them.
| Need | Use |
|---|
| Element-wise math | INLINECODE11 , np.exp, INLINECODE13 |
| Statistics |
np.mean,
np.std,
np.median |
| Linear algebra |
np.dot,
np.linalg.* |
| Sorting |
np.sort,
np.argsort |
| Searching |
np.where,
np.searchsorted |
NumPy Traps
Shape Mismatches
CODEBLOCK6
Silent Type Coercion
CODEBLOCK7
View vs Copy Confusion
CODEBLOCK8
Broadcasting Surprises
CODEBLOCK9
In-Place Operations
CODEBLOCK10
Essential Patterns
Create Arrays
CODEBLOCK11
Reshape and Stack
CODEBLOCK12
Boolean Indexing
CODEBLOCK13
Linear Algebra
CODEBLOCK14
Security & Privacy
Data that stays local:
- - All computations run locally
- Code patterns saved in ~/numpy/
This skill does NOT:
- - Send data externally
- Access files outside ~/numpy/
- Require network connectivity
Related Skills
Install with
clawhub install <slug> if user confirms:
- -
data — data processing workflows - INLINECODE25 — mathematical computations
- INLINECODE26 — statistical analysis
Feedback
- - If useful: INLINECODE27
- Stay updated: INLINECODE28
设置
首次使用时,请阅读 setup.md 了解集成指南。创建 ~/numpy/ 目录以存储偏好设置和代码片段。
使用时机
用户需要在 Python 中进行数值计算。代理使用 NumPy 处理数组操作、数学计算、线性代数和数据操作。
架构
记忆存储在 ~/numpy/ 目录中。结构参见 memory-template.md。
~/numpy/
├── memory.md # 偏好设置 + 常用模式
└── snippets/ # 用户保存的代码模式
快速参考
memory-template.md |
核心规则
1. 优先向量化
永远不要对数组操作使用 Python 循环。NumPy 的向量化操作速度快 10-100 倍。
python
错误 - Python 循环
result = []
for x in arr:
result.append(x * 2)
正确 - 向量化
result = arr * 2
2. 理解广播机制
广播允许对不同形状的数组进行操作。了解规则:
- - 维度从右对齐
- 大小为 1 的维度会拉伸以匹配
- 缺失的维度视为大小为 1
python
形状 (3,1) + (4,) 广播为 (3,4)
a = np.array([[1], [2], [3]]) # (3,1)
b = np.array([10, 20, 30, 40]) # (4,)
result = a + b # (3,4)
3. 优先使用视图而非副本
切片返回视图(共享内存)。仅在需要时使用 .copy()。
python
视图 - 修改 b 会改变 a
b = a[::2]
副本 - 独立
b = a[::2].copy()
4. 使用适当的数据类型
选择适合数据的最小数据类型。节省内存并加快计算速度。
python
对于 0-255 的整数
arr = np.array(data, dtype=np.uint8)
对于不需要双精度的浮点数
arr = np.array(data, dtype=np.float32)
5. 注意轴方向
大多数函数接受 axis 参数。了解你的轴:
- - axis=0:沿行操作(向下操作列)
- axis=1:沿列操作(横向操作行)
- axis=None 或省略:对扁平化数组操作
python
arr = np.array([[1, 2], [3, 4]])
np.sum(arr, axis=0) # [4, 6] - 每列求和
np.sum(arr, axis=1) # [3, 7] - 每行求和
6. 利用内置函数
NumPy 为常见操作提供了优化函数。不要重复造轮子。
| 需求 | 使用 |
|---|
| 逐元素数学运算 | np.sin、np.exp、np.log |
| 统计 |
np.mean、np.std、np.median |
| 线性代数 | np.dot、np.linalg.* |
| 排序 | np.sort、np.argsort |
| 搜索 | np.where、np.searchsorted |
NumPy 陷阱
形状不匹配
python
陷阱:混淆 (n,) 与 (n,1) 或 (1,n)
a = np.array([1, 2, 3]) # 形状 (3,)
b = np.array([[1, 2, 3]]) # 形状 (1,3)
c = np.array([[1], [2], [3]]) # 形状 (3,1)
修复:使用 reshape 或 newaxis
a.reshape(-1, 1) # (3,1)
a[np.newaxis, :] # (1,3)
静默类型转换
python
陷阱:整数数组静默截断浮点数
arr = np.array([1, 2, 3]) # int64
arr[0] = 1.9 # 变为 1,而不是 1.9!
修复:预先声明数据类型
arr = np.array([1, 2, 3], dtype=np.float64)
视图与副本混淆
python
陷阱:花式索引返回副本,切片返回视图
arr = np.array([1, 2, 3, 4, 5])
这是视图(更改会影响原数组)
view = arr[1:4]
这是副本(独立)
copy = arr[[1, 2, 3]]
广播意外
python
陷阱:意外的广播
a = np.array([1, 2, 3])
b = np.array([1, 2])
a + b # 错误 - 形状无法广播
陷阱:意外的广播
a = np.zeros((3, 4))
b = np.array([1, 2, 3])
a + b # 错误 - (3,4) 和 (3,) 不对齐
a + b.reshape(-1, 1) # 可行 - (3,4) 和 (3,1)
原地操作
python
陷阱:某些操作原地修改,某些不修改
np.sort(arr) # 返回排序后的副本
arr.sort() # 原地排序
安全模式:明确表达
arr = np.sort(arr) # 意图清晰
基本模式
创建数组
python
np.zeros((3, 4)) # 全零
np.ones((3, 4)) # 全一
np.full((3, 4), 7) # 全七
np.eye(3) # 单位矩阵
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
np.random.rand(3, 4) # 均匀分布 [0,1)
np.random.randn(3, 4) # 正态分布
重塑和堆叠
python
arr.reshape(2, 6) # 新形状(必须匹配大小)
arr.flatten() # 一维副本
arr.ravel() # 一维视图
np.concatenate([a, b]) # 沿现有轴连接
np.stack([a, b]) # 沿新轴连接
np.vstack([a, b]) # 垂直堆叠
np.hstack([a, b]) # 水平堆叠
布尔索引
python
arr = np.array([1, 5, 3, 8, 2])
mask = arr > 3
arr[mask] # [5, 8]
arr[arr > 3] = 0 # 将大于 3 的值替换为 0
np.where(arr > 3, 1, 0) # 大于 3 处为 1,否则为 0
线性代数
python
np.dot(a, b) # 矩阵乘法
a @ b # 同上(Python 3.5+)
np.linalg.inv(a) # 逆矩阵
np.linalg.det(a) # 行列式
np.linalg.eig(a) # 特征值/特征向量
np.linalg.solve(a, b) # 求解 Ax = b
安全与隐私
本地存储的数据:
- - 所有计算在本地运行
- 代码模式保存在 ~/numpy/ 中
此技能不会:
- - 将数据发送到外部
- 访问 ~/numpy/ 以外的文件
- 需要网络连接
相关技能
如果用户确认,使用 clawhub install
安装:
- - data — 数据处理工作流
- math — 数学计算
- statistics — 统计分析
反馈
- - 如果觉得有用:clawhub star numpy
- 保持更新:clawhub sync