{"data":{"slug":"github-opensensenova-sensenova-skills-skills-sn-da-large-file-analysis-ec4e79f956bb","title":"Large Scale Excel Analysis","summary":"Efficiently analyze large Excel files with streaming read, Parquet conversion, and memory optimization for datasets over 10,000 rows.","url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-large-file-analysis-ec4e79f956bb","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-large-file-analysis-ec4e79f956bb","markdown_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-large-file-analysis-ec4e79f956bb.md","download_url":"https:\/\/skillshunter.net\/skills\/github-opensensenova-sensenova-skills-skills-sn-da-large-file-analysis-ec4e79f956bb\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"This skill is triggered when total rows >= 10,000, or when the user mentions terms like 'large file', 'big data', 'streaming read', 'Parquet', or 'chunked processing'. It uses openpyxl's read_only mode with iter_rows for streaming, and converts to Parquet for memory efficiency.","instructions":"---\nname: sn-da-large-file-analysis\ndescription: \"\u4e07\u884c\u4ee5\u4e0a Excel \u6570\u636e\u96c6\u7684\u9ad8\u6027\u80fd\u5206\u6790\u5f15\u64ce\u3002\u63d0\u4f9b openpyxl read_only \u6d41\u5f0f\u8bfb\u53d6\uff08iter_rows \u652f\u6301 10 \u4e07\u884c\u4ee5\u4e0a\uff09\u3001Parquet \u8f6c\u6362\u52a0\u901f\u3001\u5185\u5b58\u4f18\u5316\u3001\u5206\u5757\u5904\u7406\u548c\u5927\u6587\u4ef6\u5199\u5165\u6a21\u5f0f\u3002**\u9047\u5230\u4ee5\u4e0b\u4efb\u4e00\u60c5\u51b5\u5c31\u4e3b\u52a8\u4f7f\u7528\u672c skill**\uff1a\u2460\u6570\u636e\u884c\u6570 \u2265 10k\uff08\u7531 sn-da-excel-workflow \u7684\u884c\u6570\u8bc4\u4f30\u6b65\u9aa4\u89e6\u53d1\uff09\uff1b\u2461\u7528\u6237\u51fa\u73b0\u89e6\u53d1\u8bcd\uff1a\u5927\u6587\u4ef6 \/ \u5927\u6570\u636e\u91cf \/ \u6027\u80fd\u4f18\u5316 \/ \u5185\u5b58\u4e0d\u8db3 \/ OOM \/ \u767e\u4e07\u884c \/ \u5341\u4e07\u884c \/ \u6d41\u5f0f\u8bfb\u53d6 \/ Parquet \/ \u5206\u5757\u5904\u7406 \/ large file \/ big data \/ streaming read \/ chunked processing\uff1b\u2462\u76f4\u63a5\u4f7f\u7528 pd.read_excel() \u5bfc\u81f4\u8d85\u65f6\u6216\u5185\u5b58\u6ea2\u51fa\uff1b\u2463\u7528\u6237\u660e\u786e\u8981\u6c42\u5bf9\u5927\u89c4\u6a21\u6570\u636e\u96c6\u8fdb\u884c\u9ad8\u6027\u80fd\u5904\u7406\u3002\u4ec5\u4e0d\u7528\u4e8e\uff1a\u5c0f\u4e8e 10k \u884c\u7684\u5e38\u89c4 Excel \u5206\u6790\uff08\u4f7f\u7528 sn-da-excel-workflow \u5373\u53ef\uff09\u3002\"\n---\n\n# Large Scale Excel Analysis Skill\n\n## Mandatory Rules\n\n> **When total rows >= 10,000, you MUST use the methods in this skill.**\n\n| Data Scale | Read Strategy | Reason |\n|-----------|---------------|--------|\n| < 10k rows | `pd.read_excel()` directly | No memory pressure |\n| 10k\u2013100k rows | `pd.read_excel()` \u2192 convert to Parquet \u2192 `pd.read_parquet()` for analysis | Avoid repeated slow reads |\n| 100k\u20131M rows | **openpyxl `read_only` + `iter_rows` streaming** \u2192 Parquet | `pd.read_excel()` will OOM or timeout |\n| > 1M rows | Streaming read + **multi-sheet split** (Excel max 1,048,576 rows per sheet) | Must chunk |\n\n**Prohibited:**\n- Do NOT use `pd.read_excel()` to fully load 100k+ row files\n- Do NOT search for fonts with `fc-list`, `find ... fonts`, or install packages with `pip install`\n- Do NOT use `df.iterrows()` on large DataFrames (use `itertuples()` or vectorized ops)\n- Do NOT use `df.apply(lambda...)` for operations that can be vectorized\n\n---\n\n## Environment Setup\n\n```python\nimport pandas as pd\nimport numpy as np\nimport os\nimport gc\n\npd.options.mode.copy_on_write = True\n\n# CJK font setup (fixed paths \u2014 do NOT search for fonts)\n# \u26a0\ufe0f Copy this block as-is. Do NOT use fc-list, find, subprocess, or glob to locate fonts.\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\n\n_FONT_PATHS = [\n    '\/mnt\/afs_agents\/SimHei.ttf',\n    '\/mnt\/afs_agents\/mnt\/data\/SimHei.ttf',\n    os.path.expanduser('~\/.fonts\/SimHei.ttf'),\n    '\/usr\/share\/fonts\/truetype\/wqy\/wqy-zenhei.ttc',\n    '\/usr\/share\/fonts\/SimHei.ttf',\n]\nfor _p in _FONT_PATHS:\n    if os.path.exists(_p):\n        fm.fontManager.addfont(_p)\n        matplotlib.rcParams['font.family'] = fm.FontProperties(fname=_p).get_name()\n        break\nmatplotlib.rcParams['axes.unicode_minus'] = False\n```\n\n---\n\n## Core Method 1: Inspect File Structure (Without Loading Data)\n\nBefore any operation on a large file, inspect sheets and row counts **without loading data into memory**:\n\n```python\nimport openpyxl\n\ndef inspect_excel(file_path):\n    \"\"\"Stream-inspect Excel structure. Returns {sheet_name: {rows, columns}}.\"\"\"\n    wb = openpyxl.load_workbook(file_path, read_only=True, data_only=True)\n    info = {}\n    for name in wb.sheetnames:\n        ws = wb[name]\n        row_count = 0\n        header = None\n        for i, row in enumerate(ws.iter_rows(values_only=True)):\n            if i == 0:\n                header = [str(c) if c is not None else f\"Col_{j}\" for j, c in enumerate(row)]\n            else:\n                row_count += 1\n        info[name] = {\"rows\": row_count, \"columns\": header}\n    wb.close()\n    return info\n\n# Usage\nfile_info = inspect_excel(file_path)\nfor sheet, meta in file_info.items():\n    print(f\"Sheet '{sheet}': {meta['rows']} rows, {len(meta['columns'])} cols\")\n    print(f\"  Columns: {meta['columns'][:10]}...\")\ntotal_rows = sum(m['rows'] for m in file_info.values())\nprint(f\"Total rows: {total_rows}\")\n```\n\n---\n\n## Core Method 2: Streaming Read \u2192 Parquet (100k+ Rows)\n\nFor 100k+ row files, **never** use `pd.read_excel()`. Use openpyxl streaming \u2192 Parquet:\n\n```python\nimport openpyxl\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\ndef stream_excel_to_parquet(excel_path, parquet_path, sheet_name=None, chunk_size=50000):\n    \"\"\"Stream Excel rows to Parquet with constant memory usage.\n\n    All columns are cast to string to avoid cross-chunk schema mismatches\n    (Excel mixed-type columns may be all-None in some chunks, causing PyArrow\n    to infer null type instead of string). Convert numeric columns after loading\n    Parquet with pd.to_numeric() as needed.\n    \"\"\"\n    wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)\n    ws = wb[sheet_name] if sheet_name else wb.active\n\n    header = None\n    writer = None\n    chunk_rows = []\n    total_written = 0\n\n    def _flush(rows):\n        nonlocal writer\n        table = pa.table({\n            col: pa.array(\n                [str(r[idx]) if r[idx] is not None else None for r in rows],\n                type=pa.string(),\n            )\n            for idx, col in enumerate(header)\n        })\n        if writer is None:\n            writer = pq.ParquetWriter(parquet_path, table.schema)\n        writer.write_table(table)\n\n    for i, row in enumerate(ws.iter_rows(values_only=True)):\n        if i == 0:\n            header = [str(c) if c is not None else f\"Col_{j}\" for j, c in enumerate(row)]\n            continue\n\n        chunk_rows.append(list(row))\n\n        if len(chunk_rows) >= chunk_size:\n            _flush(chunk_rows)\n            total_written += len(chunk_rows)\n            print(f\"  Written {total_written:,} rows...\")\n            chunk_rows = []\n            gc.collect()\n\n    if chunk_rows:\n        _flush(chunk_rows)\n        total_written += len(chunk_rows)\n\n    if writer:\n        writer.close()\n    wb.close()\n    print(f\"Done: {total_written:,} rows -> {parquet_path}\")\n    return total_written\n```\n\n---\n\n## Core Method 3: Medium File Parquet Conversion (10k\u2013100k Rows)\n\nFor 10k\u2013100k rows, `pd.read_excel()` won't OOM, but Parquet is much faster for repeated analysis:\n\n```python\ndef convert_excel_to_parquet(excel_path, parquet_path, sheet_name=0):\n    \"\"\"Medium file: pd.read_excel -> Parquet cache.\"\"\"\n    if os.path.exists(parquet_path):\n        print(f\"Cache exists: {parquet_path}\")\n        return\n    df = pd.read_excel(excel_path, sheet_name=sheet_name)\n    df.columns = df.columns.astype(str)\n    df.to_parquet(parquet_path, engine='pyarrow', compression='snappy')\n    row_count = len(df)\n    del df\n    gc.collect()\n    print(f\"Converted {row_count:,} rows -> {parquet_path}\")\n```\n\n---\n\n## Core Method 4: Memory Optimization (Type Downcasting)\n\nAfter loading Parquet, further reduce memory footprint:\n\n```python\ndef optimize_dtypes(df):\n    \"\"\"Auto-downcast numeric types + convert low-cardinality strings to Category.\n    Typically saves 50-80% memory.\"\"\"\n    start_mb = df.memory_usage(deep=True).sum() \/ 1024**2\n\n    for col in df.select_dtypes(include=['int64', 'int32']).columns:\n        c_min, c_max = df[col].min(), df[col].max()\n        if c_min >= np.iinfo(np.int8).min and c_max <= np.iinfo(np.int8).max:\n            df[col] = df[col].astype(np.int8)\n        elif c_min >= np.iinfo(np.int16).min and c_max <= np.iinfo(np.int16).max:\n            df[col] = df[col].astype(np.int16)\n        elif c_min >= np.iinfo(np.int32).min and c_max <= np.iinfo(np.int32).max:\n            df[col] = df[col].astype(np.int32)\n\n    for col in df.select_dtypes(include=['float64']).columns:\n        df[col] = df[col].astype(np.float32)\n\n    for col in df.select_dtypes(include=['object', 'string']).columns:\n        if df[col].nunique() \/ max(len(df), 1) < 0.5:\n            df[col] = df[col].astype('category')\n\n    end_mb = df.memory_usage(deep=True).sum() \/ 1024**2\n    print(f\"Memory: {start_mb:.1f} MB -> {end_mb:.1f} MB (saved {(1 - end_mb\/start_mb)*100:.0f}%)\")\n    return df\n```\n\n---\n\n## Core Method 5: Large File Writing\n\n```python\ndef write_large_excel(df, output_path, sheet_name=\"Sheet1\"):\n    \"\"\"Auto-select write strategy based on data size.\"\"\"\n    total_cells = len(df) * len(df.columns)\n\n    if len(df) > 1_000_000:\n        csv_path = output_path.rsplit('.', 1)[0] + '.csv'\n        df.to_csv(csv_path, index=False)\n        print(f\"Over 1M rows \u2014 exported as CSV: {csv_path}\")\n        return csv_path\n\n    if total_cells > 50_000:\n        from openpyxl import Workbook\n        from openpyxl.cell import WriteOnlyCell\n\n        wb = Workbook(write_only=True)\n        ws = wb.create_sheet(title=sheet_name)\n        ws.append(list(df.columns))\n        for idx, row in enumerate(df.itertuples(index=False)):\n            ws.append([None if pd.isna(v) else v for v in row])\n            if (idx + 1) % 100_000 == 0:\n                print(f\"  Written {idx + 1:,} rows...\")\n        wb.save(output_path)\n        wb.close()\n        print(f\"write_only mode: {len(df):,} rows -> {output_path}\")\n    else:\n        df.to_excel(output_path, index=False, sheet_name=sheet_name)\n        print(f\"Standard write: {len(df):,} rows -> {output_path}\")\n    return output_path\n```\n\n---\n\n## Example 1: 100k-Row Table \u2014 Column Distribution + Chart\n\n**Scenario**: User has a 100k-row sales Excel file and wants regional sales distribution with a bar chart.\n\n```python\nimport pandas as pd\nimport os, gc\n\nexcel_path = \"sales_100k.xlsx\"\nparquet_path = \"sales_100k.parquet\"\n\n# === Step 1: Inspect structure ===\nfile_info = inspect_excel(excel_path)\ntotal_rows = sum(m['rows'] for m in file_info.values())\nprint(f\"Total rows: {total_rows}\")\n\n# === Step 2: Choose read strategy by row count ===\nif total_rows >= 100_000:\n    stream_excel_to_parquet(excel_path, parquet_path)\nelse:\n    convert_excel_to_parquet(excel_path, parquet_path)\n\n# === Step 3: Load Parquet + optimize memory ===\ndf = pd.read_parquet(parquet_path)\ndf = optimize_dtypes(df)\nprint(f\"Shape: {df.shape}\")\nprint(df.head(3))\n\n# === Step 4: Analysis ===\nregion_sales = df.groupby('Region')['Sales'].sum().sort_values(ascending=False)\nprint(region_sales)\n\n# === Step 5: Visualization ===\nfig, ax = plt.subplots(figsize=(10, 6))\nregion_sales.plot(kind='bar', ax=ax, color='#4C72B0')\nax.set_title('Sales by Region')\nax.set_ylabel('Sales')\nplt.tight_layout()\nplt.savefig('region_sales.png', dpi=150, bbox_inches='tight')\nplt.show()\n\n# === Step 6: Cleanup ===\ndel df\ngc.collect()\n```\n\n---\n\n## Example 2: 1M-Row Table \u2014 Streaming Read + Filter + Export\n\n**Scenario**: User has a 1M-row transaction log and wants records with amount > 10,000 exported.\n\n```python\nimport pandas as pd\nimport os, gc\n\nexcel_path = \"transactions_1m.xlsx\"\nparquet_path = \"transactions_1m.parquet\"\n\n# === Step 1: Stream to Parquet (1M rows \u2014 MUST use streaming, never pd.read_excel) ===\nstream_excel_to_parquet(excel_path, parquet_path, chunk_size=50000)\n\n# === Step 2: Load only needed columns (saves memory) ===\ndf = pd.read_parquet(parquet_path, columns=['TransactionID', 'Amount', 'Date', 'Type'])\ndf = optimize_dtypes(df)\nprint(f\"Shape: {df.shape}, Memory: {df.memory_usage(deep=True).sum()\/1024**2:.1f} MB\")\n\n# === Step 3: Vectorized filtering (never use apply\/iterrows) ===\nmask = df['Amount'] > 10000\nhigh_value = df[mask].copy()\nprint(f\"Filtered: {len(high_value):,} \/ {len(df):,} rows\")\n\n# === Step 4: Export ===\noutput_path = write_large_excel(high_value, 'high_value_transactions.xlsx')\n\n# === Step 5: Cleanup ===\ndel df, high_value\ngc.collect()\n```\n\n---\n\n## Vectorized Operations Cheat Sheet\n\nOn large files, **never use slow operations** \u2014 use vectorized alternatives:\n\n| Slow (Prohibited) | Fast (Use This) |\n|-------------------|-----------------|\n| `df.apply(lambda x: x*2)` | `df['col'] * 2` |\n| `df.iterrows()` | `df.itertuples(index=False)` |\n| `for i in range(len(df)): df.iloc[i]` | Vectorized boolean indexing `df[mask]` |\n| `df['a'].map(lambda x: 'Y' if x>0 else 'N')` | `np.where(df['a']>0, 'Y', 'N')` |\n| `df.groupby('a').apply(custom_func)` | `df.groupby('a').agg({'b':'sum','c':'mean'})` |\n\n---\n\n## Memory Estimation\n\nEstimate memory before loading to avoid OOM:\n\n```\nEstimated MB \u2248 rows \u00d7 cols \u00d7 8 \/ 1024\u00b2 (numeric columns)\nEstimated MB \u2248 rows \u00d7 cols \u00d7 50 \/ 1024\u00b2 (with text columns)\n```\n\n| Rows | 20 cols (numeric) | 20 cols (with text) |\n|------|-------------------|---------------------|\n| 100k | ~15 MB | ~95 MB |\n| 500k | ~76 MB | ~477 MB |\n| 1M | ~153 MB | ~953 MB |\n\nWhen estimated memory exceeds 80% of available RAM, use **column-selective loading** (`pd.read_parquet(columns=[...])`) or chunked processing.\n\n---\n\n## Best Practices\n\n1. **Parquet is king**: For any file >= 10k rows, convert to Parquet before analysis. Parquet supports columnar reads, compressed storage, and loads 10-50x faster than xlsx.\n2. **Streaming is the safety net**: For 100k+ rows, always use openpyxl `read_only` + `iter_rows`. Never `pd.read_excel()` for full load.\n3. **Release memory promptly**: `del df; gc.collect()` after every intermediate DataFrame.\n4. **Excel row limit**: Max 1,048,576 rows per sheet. Auto-split to multiple sheets or export as CSV when exceeded.\n5. **Use write_only for output**: Files with >50k cells must use `openpyxl Workbook(write_only=True)`.\n","use_cases":["Analyzing Excel files with over 100,000 rows without memory overflow","Converting large Excel files to Parquet for faster analysis","Streaming read of Excel files to avoid memory issues"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/OpenSenseNova\/SenseNova-Skills\/blob\/07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b\/skills\/sn-da-large-file-analysis\/SKILL.md","source_commit":"07e7ff8c4bdfd7b79e7402fe94af59d2a5a9749b","license":null,"version":null,"listing_approved_at":"2026-11-16","created_at":"2026-11-15T10:08:44.000000Z","updated_at":"2026-11-16T05:16:30.000000Z","seo_title":"Large Excel File Analysis Tool","seo_description":"Perform high-performance analysis on large Excel files with streaming read, Parquet conversion, and memory optimization for datasets over 10,000 rows.","seo_keywords":["large Excel file analysis","streaming Excel read","Parquet conversion for Excel","memory efficient Excel processing"]}}