К основному содержанию
скилл CX Codex

csv-excel-merger — скилл для Claude Code: объединяет CSV и Excel

Скилл складывает несколько CSV, TSV и Excel в один файл: склеивает, джойнит по ключу, убирает дубли и проверяет арифметику строк.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add OneWave-AI/claude-skills --skill csv-excel-merger -a claude-code
Открыть на GitHub

Что делает csv-excel-merger

Скилл работает через pandas и берёт на себя рутину, на которой обычно теряются строки: приводит разные названия колонок к одной схеме, чистит ключи (пробелы, регистр почты, формат дат), решает конфликты значений и помечает каждую строку источником. Внутри — скрипт scripts/profile_inputs.py, который сначала показывает кодировку, разделитель, число строк и пересечение заголовков, ничего не меняя. Дальше вы выбираете операцию: append для однотипных выгрузок за разные месяцы, join для данных об одних и тех же сущностях по ID или email.

Читает файлы с dtype=str, поэтому ведущие нули в ID, индексах и телефонах не теряются. Для join есть validate="one_to_one" — если ключ дублируется, pandas упадёт с ошибкой вместо размножения строк. Перед выдачей результата скилл проверяет арифметику: сколько строк вошло, сколько вышло, сколько удалено и сколько осталось с пустым ключом. Пустые ключи он не считает дублями друг друга и откладывает отдельно.

Нужен Python и pandas; для чтения Excel — openpyxl, а engine="calamine" с python-calamine заметно ускоряет большие книги. Учтите: значения, которые Excel уже испортил в исходнике (длинный ID как 1.23E+15 или переформатированная дата), pandas не восстановит — их только помечают. Один лист Excel держит максимум 1,048,576 строк, дальше придётся разбивать или брать CSV. Файлы крупнее нескольких сотен МБ читайте через chunksize= или Polars с DuckDB.

Какие задачи решает

  • склеить выгрузки за январь и февраль в один файл
  • соединить контакты с суммами сделок по email
  • убрать дубли записей из трёх источников
  • свести разные названия колонок к одной схеме
  • проверить, не размножились ли строки после join

Примеры запросов агенту

  • Объедини jan.csv и feb.xlsx в один файл, колонки E-mail и Email Address — это email
  • Сделай VLOOKUP-джойн contacts.csv и deals.xlsx по email, покажи, кто остался без сделки
  • Убери дубли в трёх списках лидов и добавь колонку с именем исходного файла

Как установить csv-excel-merger

1Через Skills CLI (Vercel)

npx skills add OneWave-AI/claude-skills --skill csv-excel-merger -a claude-code

2Вручную: положить файлы

~/.claude/skills/csv-excel-merger/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/csv-excel-merger/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора58

landing-page-copywriter Скилл пишет тексты для лендингов, списков ожидания и страниц тарифов по формулам PAS, AIDA или StoryBrand. Помогает подготовить конверсионные блоки и варианты CTA без написания вёрстки. CX Codex +1 6 500установок code-review-pro Разбирает файлы, модуль, диф или ветку и выдаёт находки по критичности: уязвимости, баги, узкие места, проблемы поддержки. С доказательствами и готовыми правками. CX Codex +1 2 600установок screenshot-to-code Превращает скриншот, макет или экспорт из Figma в рабочий фронтенд-код и сверяет результат с картинкой. Пригодится, когда есть дизайн, но нет вёрстки. CX Codex +1 1 300установок technical-writer Пишет и переписывает README, туториалы, how-to, runbook и release notes, опираясь на реальный код. Пригодится, когда проект надо объяснить новым разработчикам. CX Codex +1 1 000установок sports-betting-analyzer Разбирает спреды, тоталы и проп-ставки на основе исторических трендов и ситуационной статистики. Подходит для образовательного анализа спортивных рынков. CX Codex +1 808установок css-animation-creator Скилл для ИИ-кодинга, который помогает писать CSS-анимации, переходы, микроинтеракции и анимации по скроллу. Пригодится, когда нужно добавить движение в интерфейс без ручного подбора таймингов. CX Codex +1 805установок job-application-optimizer Скилл подгоняет резюме под конкретную вакансию, пишет сопроводительное письмо и готовит вопросы к собеседованию. Пригодится, когда отклик нужно отправить сегодня. CX Codex +1 698установок knowledge-base-builder Разбирает тикеты поддержки, находит повторяющиеся вопросы и собирает из них статьи базы знаний, туториалы и скрипты для видео. CX Codex +1 667установок

Похожие

Skywork Excel SkyworkAI Создаёт и анализирует таблицы Excel, строит графики и сводные отчёты через бэкенд Skywork. Пригодится для подготовки финмоделей и конвертации PDF в таблицы. CX Codex +1 361установок dwg-to-excel datadrivenconstruction Конвертирует чертежи AutoCAD DWG в базы данных Excel и PDF через утилиту DwgExporter. Пригодится, когда нужно выгрузить слои, блоки и геометрию без покупки лицензий Autodesk. CX Codex +1 308установок excel-automation daymade Создаёт отчёты Excel через openpyxl, читает сложные модели xlsm через zipfile и управляет окном приложения на macOS. Пригодится для финотчётов и переноса бумажных бланков в таблицы. CX Codex +1 1 500установок convert-excel-to-md официальный github Преобразует книги Excel .xlsx в Markdown для чтения, поиска и разбора данных. Срабатывает при запросах о таблицах, даже без явной просьбы о конвертации. 88установок csv-formula-injection yaklang Скилл для проверки того, как выгрузки в CSV и таблицы реагируют на формулы из пользовательских полей. Нужен при тестировании отчётов и экспортов. CX Codex +1 3 600установок clean-data-xls официальный anthropics Скилл автоматизирует уборку грязных данных в Excel и Google Sheets: убирает пробелы, унифицирует регистр, конвертирует числа из текста, стандартизирует даты, удаляет дубликаты и выявляет колонки со смешанными типами. CX Codex +1 2 100установок

Рядом в теме «Данные и базы»

Все скиллы по теме «Данные и базы» →

Вопросы о csv-excel-merger

Как установить csv-excel-merger в Claude?

Выполните npx skills add OneWave-AI/claude-skills --skill csv-excel-merger -a claude-code. Скилл встанет в ~/.claude/skills/csv-excel-merger/SKILL.md.

Что делает csv-excel-merger?

Объединяет CSV, TSV и Excel в один выходной файл: склеивает, джойнит по ключу, убирает дубли и проверяет, что число строк не выросло и не потерялось.

Какая версия pandas нужна?

Код рассчитан на pandas 3.x с Python 3.11+, но работает и на pandas 2.2. В 3.x текстовые колонки получают тип str, а Copy-on-Write включён всегда — цепочка вида df[col][mask] = x молча ничего не изменит, нужен df.loc[mask, col] = x.

Исходный текст

SKILL.md · MIT
---
name: csv-excel-merger
description: Merges, appends, joins, and deduplicates multiple CSV, TSV, and Excel files (including multi-sheet workbooks) with pandas - mapping mismatched column names to one schema, normalizing keys, resolving conflicting values, tracking which file each row came from, and verifying the row math. Use when the user wants to combine spreadsheets or exports, stack monthly files, consolidate contact or lead lists, VLOOKUP-style join two sheets on an ID or email, or dedupe records across sources, even if they only say "put these together" or "clean up these lists into one".
---

# CSV/Excel Merger

Combine tabular files into one clean output without silently losing, duplicating, or corrupting rows.

## Workflow

Copy this checklist and track progress:

```
- [ ] 1. Profile inputs
- [ ] 2. Choose append vs join
- [ ] 3. Map columns and normalize keys
- [ ] 4. Merge and resolve conflicts
- [ ] 5. Verify row math
- [ ] 6. Write output and report
```

1. **Profile inputs.** Run the bundled profiler first; it reports encoding, delimiter, rows, headers, candidate keys, and header overlap without changing anything:

   ```bash
   python scripts/profile_inputs.py file1.csv file2.xlsx
   ```

   Excel files are profiled per sheet. Confirm with the user which sheets count if a workbook has more than one.

2. **Choose the operation.** This is the decision that most often goes wrong:
   - **Append (stack)** - same kind of records from different sources or periods (Jan + Feb exports, three lead lists). Use `pd.concat`, then dedupe.
   - **Join (enrich)** - different facts about the same entities (contacts + their deal values). Use `pd.merge` on a key.
   - Unsure? If the files share most columns, append. If they share only an ID column, join.

3. **Map columns and normalize keys.** Build an explicit `{original: unified}` rename map per file (see [references/merge_strategies.md](references/merge_strategies.md) for common variants) and show it to the user when any match is fuzzy. Normalize key columns before dedupe or join: strip whitespace, lowercase emails, strip non-digits from phones, unify date formats. Without this, `[email protected] ` and `[email protected]` survive as two people.

4. **Merge.** Read every file with `dtype=str` so IDs, ZIP codes, and phone numbers keep leading zeros, then convert specific columns afterward.

   ```python
   import pandas as pd

   frames = []
   for path, rename in [("jan.csv", {"E-mail": "email"}), ("feb.xlsx", {"Email Address": "email"})]:
       df = (pd.read_excel(path, dtype=str) if path.endswith((".xlsx", ".xls"))
             else pd.read_csv(path, dtype=str, encoding="utf-8-sig",  # use the profiler's encoding
                           keep_default_na=False))
       df = df.rename(columns=rename)
       df["email"] = df["email"].str.strip().str.lower()
       df["source_file"] = path          # lineage for every row
       frames.append(df)

   combined = pd.concat(frames, ignore_index=True, sort=False)
   # Blank keys are not duplicates of each other: set them aside before deduping.
   has_key = combined["email"].fillna("") != ""
   # Later files win: list the most recent source last, then keep="last".
   deduped = combined[has_key].drop_duplicates(subset=["email"], keep="last")
   no_key = combined[~has_key]
   merged = pd.concat([deduped, no_key], ignore_index=True)
   ```

   For a join, make pandas enforce the relationship you expect so a duplicate key raises instead of multiplying rows:

   ```python
   out = pd.merge(contacts, deals, on="email", how="left",
                  validate="one_to_one", indicator=True)
   unmatched = out[out["_merge"] == "left_only"]
   ```

   Conflict strategies (keep first/last/most complete, combine fields, flag for review) are in [references/merge_strategies.md](references/merge_strategies.md).

5. **Verify before reporting.** Never hand back a merge without checking it:

   ```python
   rows_in = sum(len(f) for f in frames)
   assert len(merged) > 0, "merge produced an empty frame"
   assert len(merged) <= rows_in, "more rows out than in: check the join keys"
   assert deduped["email"].is_unique, "duplicate keys remain after dedupe"
   print(f"in={rows_in} out={len(merged)} removed={rows_in - len(merged)} blank_keys={len(no_key)}")
   print(merged["source_file"].value_counts())
   ```

   Spot-check three removed duplicates by hand against the source files; the asserts prove the math, not that the right row won.

6. **Write output and report.** Use the layout in [references/output_template.md](references/output_template.md).
   - CSV for Excel users: `to_csv(path, index=False, encoding="utf-8-sig")` (the BOM makes Excel read accents correctly).
   - Excel: `to_excel(path, index=False)` with openpyxl installed. A sheet holds at most 1,048,576 rows; split or use CSV/Parquet beyond that.
   - Also write `conflicts_review.csv` or `unmatched.csv` when those sets are non-empty.

## pandas version notes

Current pandas is 3.x (Python 3.11+). Differences that affect merges:
- Text columns default to the `str` dtype, not `object`. Check `pd.api.types.is_string_dtype(col)` instead of `dtype == object`.
- Copy-on-Write is always on. Chained assignment such as `df[col][mask] = x` never updates `df` (pandas only warns); use `df.loc[mask, col] = x`.
- Parsed datetimes default to microsecond resolution. Call `.dt.as_unit("ns")` before casting to integers if something downstream expects nanoseconds.
- `pd.read_excel(..., engine="calamine")` (needs `python-calamine`) reads large workbooks much faster than openpyxl.

The code in this skill also runs on pandas 2.2.

## Failure modes to check for

- **Row explosion on join** - duplicate keys on both sides multiply rows. `validate=` catches it.
- **Leading zeros lost** - reading without `dtype=str` turns `01234` into `1234`.
- **Excel-mangled values** - long IDs already shown as `1.23E+15` or dates already reformatted in the source file cannot be recovered by pandas; flag them.
- **Header rows not on line 1** - exports with a title block need `skiprows=` or `header=`.
- **Mixed encodings** - one file in cp1252 among UTF-8 files shows up as `é` artifacts. The profiler reports the encoding per file.
- **Silent column drops** - a column present in only one file becomes mostly empty after append. Keep it and report its completeness; never drop data without saying so.
- **Large files** (over a few hundred MB) - read with `chunksize=` or use Polars/DuckDB, and dedupe with a key set instead of loading everything into memory.

© OneWave-AI · MIT · OneWave-AI/claude-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой