用途
该技能面向数据科学与机器学习代码,提供 NumPy 和 pandas 的最佳实践,专为 AI 智能体与 LLM 设计,目标是编写快速、正确且可复现的数值代码。
数值代码有其不同于通用 Python 的惯用法:循环是反模式,数据结构是不可变缓冲区,dtype 是一项设计决策。当本技能中的规则与编码规范规则重叠时,对于数组和 DataFrame 代码,本技能优先。
主要能力
技能按类别组织规则,并标注严重程度:
- 向量化 [CRITICAL]:将计算保留在编译后的 NumPy/pandas 代码中,而非 Python 解释器。规则包括 vec-no-python-loops(用向量化替代 Python 循环、iterrows 和逐行 apply,快 10-1000 倍)、vec-no-incremental-growth(一次性构建数组和 DataFrame,而非增量构建,O(n) 对比 O(n²))。
- 索引与修改 [CRITICAL]:在 Copy-on-Write 下以正确方式写入 DataFrame,并在数据流中可见。规则包括 mut-loc-not-chained(用 .loc 赋值,绝不用链式索引)、mut-no-inplace(避免 inplace=True)。
- 数据类型 [HIGH]:让 dtype 成为显式决策而非推断结果。规则包括 dtype-explicit-io(加载数据时指定 dtype)、dtype-categorical(对低基数文本使用 category dtype)、dtype-numpy-explicit(显式选择 NumPy dtype)。
- 模式校验 [HIGH]:在表格数据进入系统处进行校验。规则包括 schema-pandera(在边界处用 pandera 校验 DataFrame)。
- 可复现性 [HIGH]:让实验可重复且无隐藏全局状态。规则包括 repro-default-rng(使用显式 Generator 处理随机性)。
- 转换风格 [MEDIUM]:让 DataFrame 转换自上而下读起来像单一管道。规则包括 style-method-chaining(将转换表达为方法链)、style-named-aggregation(在 groupby 中使用命名聚合)。
- 类型标注 [MEDIUM]:携带 dtype 和列信息的类型提示。规则包括 type-array-annotations(用精确类型标注数组和帧)。
- 测试 [MEDIUM]:适配浮点数组和 DataFrame 的断言。规则包括 test-numeric-assertions(用容差感知断言比较数值结果)。
使用方式
技能提供快速参考代码示例,覆盖各主要类别:
向量化:
# Whole-array operations, not loops / iterrows / apply(axis=1)
df["total"] = df["price"] * df["qty"]
rate = np.select([df["qty"] >= 100, df["qty"] >= 10], [0.2, 0.1], default=0.0)
# Collect, then build once
records = [{"id": item.id, "score": score(item)} for item in items]
results = pd.DataFrame.from_records(records)
combined = pd.concat(frames, ignore_index=True)
索引与修改:
# .loc in one step; chained assignment never reaches df under Copy-on-Write
df.loc[df["status"] == "pending", "priority"] = "high"
# Returning form, not inplace=True
df = df.dropna(subset=["email"]).sort_values("created_at")
数据类型:
df = pd.read_csv(
path,
dtype={"customer_id": "Int64", "zip_code": "string", "region": "category"},
parse_dates=["created_at"],
)
SEVERITY = pd.CategoricalDtype(["low", "medium", "high"], ordered=True)
embeddings = np.zeros((n, 768), dtype=np.float32)
模式校验:
import pandera.pandas as pa
from pandera.typing import DataFrame, Series
class OrderSchema(pa.DataFrameModel):
order_id: Series[int] = pa.Field(unique=True)
price: Series[float] = pa.Field(ge=0)
class Config:
strict = True
def load_orders(path: str) -> DataFrame[OrderSchema]:
return OrderSchema.validate(pd.read_csv(path))
可复现性:
def run_experiment(seed: int) -> Result:
rng = np.random.default_rng(seed)
split_rng, noise_rng = rng.spawn(2)
...
def add_noise(x: np.ndarray, rng: np.random.Generator) -> np.ndarray:
return x + rng.normal(scale=0.1, size=x.shape)
转换风格:
monthly = (
pd.read_csv("sales.csv", parse_dates=["date"])
.assign(
revenue=lambda d: d["price"] * d["qty"],
month=lambda d: d["date"].dt.to_period("M"),
)
.loc[lambda d: d["revenue"] > 0]
.groupby("month", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
)
类型标注:
import numpy.typing as npt
def to_float32(values: npt.ArrayLike) -> npt.NDArray[np.float32]:
return np.asarray(values, dtype=np.float32)
测试:
np.testing.assert_allclose(result, expected, rtol=1e-6, atol=1e-12)
pd.testing.assert_frame_equal(result_df, expected_df, check_like=True)
适用场景
适用于编写数据科学与机器学习中的数值代码,尤其是使用 NumPy 和 pandas 进行数组与 DataFrame 操作的场景,包括数据加载、清洗、转换、聚合、随机实验和数值测试。
限制
资料未提供该技能的安装方式、收费信息、平台支持范围或具体使用步骤。资料中提及的相关技能包括 coding-standards(通用 Python 规则,其中 validation-pydantic、design-no-global-singleton 和 doc-type-hints 在此有直接对应项)以及 testing(数值测试仍遵循的 pytest 结构、fixture 和 mock)。