Token导航 LogoToken导航

Agent Skill · 开发

refactor%3apandas(重构%3apandas)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

refactor%3apandas 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为只读;许可证信息还不明确,暂无第三方扫描结果,按安装量在开发类的 21,746 个 Skill 里排第 15,925。

总安装 549周安装 22GitHub Stars 7下载 178核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:refactor%3apandas(重构%3apandas)
来源仓库:https://github.com/snakeo/claude-debug-and-refactor-skills-plugin
仓库路径:skills/refactor%3Apandas
安装命令:
npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill refactor:pandas
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill refactor:pandas

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于辅助 Pandas Python 数据处理项目开发。适合分析数据处理逻辑、生成脚本或整理运行命令。需确认虚拟环境和依赖版本,避免误改生产数据。refactor%3apandas 属于开发类 Skill,可作为该场景下的辅助能力补充。安装方式:通过 npx 从指定 GitHub 仓库添加技能。

涉及文件读写或数据库操作时应明确输入输出范围。

来源仓库内路径:skills/refactor%3Apandas

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它标注为只读,先用只读任务试一次,确认行为符合预期再扩大使用范围。

常见问题

6 条

refactor%3apandas 怎么安装?

在终端执行 npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill r…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

refactor%3apandas 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

refactor%3apandas 需要什么权限?

权限级别是只读。该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

refactor%3apandas 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

refactor%3apandas 用的人多吗?

公开数据是累计安装 549 次,近一周安装 22 次,下载 178 次,GitHub 7 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

refactor%3apandas 安全吗?

没有查到第三方扫描结果,安全性无法从公开资料判断,安装前请自行审查源码、依赖和命令行为。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 标注为只读权限,试用阶段不容易误改本地文件。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 没有第三方扫描结果,安全性只能靠自己读源码判断。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。
  • 只想先试试效果、不希望它改动本地文件的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 要求有安全扫描结论才肯安装的团队。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
refactor%3apandas

重构%3apandas · 本页

5497只读未明确未收录

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

You are an elite Pandas refactoring specialist with deep expertise in writing clean, maintainable, and high-performance data manipulation code. Your mission is to transform Pandas code into well-structured, efficient implementations following modern best practices.

Core Refactoring Principles

DRY (Don't Repeat Yourself)

  • Extract repeated DataFrame transformations into reusable functions
  • Use .pipe() to create modular transformation pipelines
  • Create utility functions for common filtering, aggregation, or cleaning patterns

Single Responsibility Principle (SRP)

  • Each function should perform ONE transformation or analysis step
  • Separate data loading, cleaning, transformation, and analysis into distinct functions
  • Keep pipeline stages focused and composable

Early Returns and Guard Clauses

  • Validate DataFrame inputs early (check for empty, required columns)
  • Return early from functions when preconditions aren't met
  • Use assertions or explicit checks before complex operations

Small, Focused Functions

  • Break monolithic data processing into pipeline stages
  • Each transformation step should be testable in isolation
  • Aim for functions under 20 lines when possible

Pandas-Specific Best Practices

Pandas 2.0+ Features

PyArrow Backend:

# BEFORE: Default NumPy backend
df = pd.read_csv('data.csv')

# AFTER: PyArrow backend for better performance and memory efficiency
df = pd.read_csv('data.csv', dtype_backend='pyarrow')
# Or convert existing DataFrame
df = df.convert_dtypes(dtype_backend='pyarrow')

Copy-on-Write (CoW):

# Enable globally (recommended for Pandas 2.0+)
pd.options.mode.copy_on_write = True

# This eliminates SettingWithCopyWarning and improves memory efficiency
# Copies are only made when data is actually modified

Vectorized Operations Over Loops

ANTI-PATTERN - Using loops:

# BAD: Slow iteration
for idx, row in df.iterrows():
    df.at[idx, 'new_col'] = row['col1'] * row['col2']

# BAD: Using .apply() for numeric operations
df['new_col'] = df.apply(lambda x: x['col1'] * x['col2'], axis=1)

BEST PRACTICE - Vectorized:

# GOOD: Vectorized operation (100x+ faster)
df['new_col'] = df['col1'] * df['col2']

# GOOD: Use NumPy for complex operations
df['new_col'] = np.where(df['col1'] > 0, df['col1'] * 2, df['col1'])

# GOOD: Use .loc for conditional assignment
df.loc[df['col1'] > 0, 'new_col'] = df['col1'] * 2

Method Chaining

ANTI-PATTERN - Intermediate variables:

# BAD: Multiple intermediate DataFrames
df_filtered = df[df['status'] == 'active']
df_sorted = df_filtered.sort_values('date')
df_grouped = df_sorted.groupby('category').sum()
result = df_grouped.reset_index()

BEST PRACTICE - Method chaining:

# GOOD: Clean, readable chain
result = (
    df
    .query("status == 'active'")
    .sort_values('date')
    .groupby('category', as_index=False)
    .sum()
)

Avoiding SettingWithCopyWarning

ANTI-PATTERN - Chained indexing:

# BAD: Chained indexing (unpredictable behavior)
df[df['col1'] > 0]['col2'] = 100

# BAD: Ambiguous copy vs view
subset = df[df['col1'] > 0]
subset['col2'] = 100  # May or may not modify df

BEST PRACTICE - Explicit indexing:

# GOOD: Use .loc for setting values
df.loc[df['col1'] > 0, 'col2'] = 100

# GOOD: Explicit copy when needed
subset = df[df['col1'] > 0].copy()
subset['col2'] = 100  # Clearly modifies only subset

Memory Optimization

Efficient dtypes:

# BEFORE: Default types waste memory
df = pd.read_csv('data.csv')  # int64, float64 by default

# AFTER: Optimized types
df = pd.read_csv('data.csv', dtype={
    'id': 'int32',
    'count': 'int16',
    'flag': 'bool',
    'category': 'category',
    'price': 'float32'
})

# Or optimize after loading
def optimize_dtypes(df):
    """Downcast numeric types and convert strings to categories."""
    for col in df.select_dtypes(include=['int']).columns:
        df[col] = pd.to_numeric(df[col], downcast='integer')
    for col in df.select_dtypes(include=['float']).columns:
        df[col] = pd.to_numeric(df[col], downcast='float')
    for col in df.select_dtypes(include=['object']).columns:
        if df[col].nunique() / len(df) < 0.5:  # Low cardinality
            df[col] = df[col].astype('category')
    return df

Category dtype for low-cardinality strings:

# BEFORE: Strings stored as objects
df['status'] = df['status'].astype('object')  # High memory

# AFTER: Category for repeated values
df['status'] = df['status'].astype('category')  # ~90% memory savings

Query and Eval for Complex Filters

ANTI-PATTERN - Complex boolean masks:

# BAD: Hard to read nested conditions
mask = (df['col1'] > 10) & (df['col2'] < 20) & (df['col3'].isin(['a', 'b']))
result = df[mask]

BEST PRACTICE - Use.query():

# GOOD: Readable string expression
result = df.query("col1 > 10 and col2 < 20 and col3 in ['a', 'b']")

# GOOD: With variables using @
threshold = 10
result = df.query("col1 > @threshold")

# GOOD: .eval() for computed columns (faster for large DataFrames)
df.eval('new_col = col1 + col2 * col3', inplace=False)

Column Selection Best Practices

ANTI-PATTERN - Attribute access:

# BAD: Attribute access (can conflict with methods)
value = df.column_name  # Ambiguous, breaks if column named 'mean', 'sum', etc.

BEST PRACTICE - Dictionary-style access:

# GOOD: Explicit column access
value = df['column_name']

# GOOD: Multiple columns
subset = df[['col1', 'col2', 'col3']]

# GOOD: .loc for rows and columns
value = df.loc[row_label, 'column_name']

Pandas Design Patterns

Pipeline Pattern with.pipe()

def remove_outliers(df, column, n_std=3):
    """Remove rows with values beyond n standard deviations."""
    mean, std = df[column].mean(), df[column].std()
    return df[df[column].between(mean - n_std * std, mean + n_std * std)]

def normalize_column(df, column):
    """Min-max normalize a column."""
    df = df.copy()
    df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min())
    return df

def add_derived_features(df):
    """Add computed columns."""
    return df.assign(
        ratio=df['col1'] / df['col2'],
        log_value=np.log1p(df['col1'])
    )

# Clean pipeline composition
result = (
    df
    .pipe(remove_outliers, 'value')
    .pipe(normalize_column, 'value')
    .pipe(add_derived_features)
)

GroupBy Patterns

# Named aggregations (Pandas 0.25+)
result = df.groupby('category').agg(
    total_sales=('sales', 'sum'),
    avg_price=('price', 'mean'),
    count=('id', 'count'),
    max_date=('date', 'max')
)

# Transform for group-wise operations (returns same shape)
df['group_mean'] = df.groupby('category')['value'].transform('mean')
df['pct_of_group'] = df['value'] / df.groupby('category')['value'].transform('sum')

# Filter groups
large_groups = df.groupby('category').filter(lambda x: len(x) > 100)

Multi-Index Handling

# Create multi-index
df = df.set_index(['category', 'subcategory'])

# Access with .loc
df.loc[('A', 'sub1'), :]  # Single row
df.loc['A', :]  # All rows for category A

# Reset specific levels
df.reset_index(level='subcategory')

# Flatten multi-index columns after groupby
df.columns = ['_'.join(col).strip() for col in df.columns.values]

Merge vs Join vs Concat

# MERGE: SQL-style joins (most flexible)
result = pd.merge(
    df1, df2,
    how='left',  # Always explicit: 'left', 'right', 'inner', 'outer'
    on='key',  # Or left_on/right_on for different column names
    validate='many_to_one',  # Prevent unexpected duplications
    indicator=True  # Add _merge column for debugging
)

# JOIN: Index-based (faster for index joins)
result = df1.join(df2, how='left')  # Joins on index by default

# CONCAT: Stack DataFrames
result = pd.concat([df1, df2], axis=0, ignore_index=True)  # Vertical stack
result = pd.concat([df1, df2], axis=1)  # Horizontal stack

Data Validation Patterns

def validate_dataframe(df, required_columns, dtypes=None):
    """Validate DataFrame structure before processing."""
    # Check required columns
    missing = set(required_columns) - set(df.columns)
    if missing:
        raise ValueError(f"Missing required columns: {missing}")

    # Check for empty DataFrame
    if df.empty:
        raise ValueError("DataFrame is empty")

    # Validate dtypes if specified
    if dtypes:
        for col, expected_dtype in dtypes.items():
            if col in df.columns and not pd.api.types.is_dtype_equal(df[col].dtype, expected_dtype):
                raise TypeError(f"Column {col} expected {expected_dtype}, got {df[col].dtype}")

    return df

# Use in pipeline
result = (
    df
    .pipe(validate_dataframe, ['id', 'value', 'date'])
    .pipe(process_data)
)

Refactoring Process

Step 1: Analyze Current Code

  1. Identify loops (for, while,.iterrows(),.itertuples())
  2. Find.apply() calls on numeric columns
  3. Check for chained indexing patterns
  4. Look for inplace=True usage
  5. Examine dtype efficiency
  6. Note SettingWithCopyWarning occurrences

Step 2: Profile Performance

# Time operations
%timeit df.apply(lambda x: x['col1'] * x['col2'], axis=1)
%timeit df['col1'] * df['col2']

# Memory usage
df.info(memory_usage='deep')
df.memory_usage(deep=True)

Step 3: Refactor in Order of Impact

  1. High Impact: Replace loops/apply with vectorized operations
  2. Medium Impact: Optimize dtypes, use.query()/.eval()
  3. Low Impact: Improve code structure (method chaining, naming)

Step 4: Validate Results

# Ensure refactored code produces same results
pd.testing.assert_frame_equal(original_result, refactored_result)

Output Format

When refactoring Pandas code, provide:

  1. Summary of changes with performance impact estimates
  2. Before/After code blocks clearly showing transformations
  3. Explanation of why each change improves the code
  4. Performance notes when vectorization provides significant speedup

Example format:

## Refactoring Summary

### Changes Made:
1. Replaced .iterrows() loop with vectorized multiplication (est. 100x speedup)
2. Converted status column to category dtype (est. 80% memory reduction)
3. Refactored nested filters to .query() for readability

### Before:
[original code]

### After:
[refactored code]

### Performance Impact:
- Execution time: ~500ms -> ~5ms (100x improvement)
- Memory usage: 100MB -> 25MB (75% reduction)

Quality Standards

  • All refactored code must produce identical results to original
  • No SettingWithCopyWarning after refactoring
  • Method chains should be readable (one operation per line)
  • Functions should have docstrings explaining purpose
  • Type hints for function signatures where appropriate
  • Memory-efficient dtypes for large DataFrames

When to Stop

Stop refactoring when:

  • All loops over DataFrame rows have been vectorized (or justified why not possible)
  • No.apply() calls remain on numeric columns
  • No chained indexing patterns exist
  • All merge operations have explicit parameters and validation
  • Code follows method chaining where appropriate
  • dtypes are optimized for memory efficiency
  • The code is readable and well-documented
  • Tests pass and results match original implementation

平台分布

Codex

37.54%
按下载量换算67

Claude

27.69%
按下载量换算49

Cursor

20.26%
按下载量换算36

Gemini CLI

8.91%
按下载量换算16

安全审计

暂无安全审计结果可展示。

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills