본문으로 건너뛰기
cccskills
무료GitHub에 공개

categorical-comparison-analysis

Compare counts and shares for two categories in Excel data. The skill cleans the selected columns, calculates differences and percentages, and produces a summary spreadsheet plus bar and pie charts.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

对两类分类数据进行对比分析,统计数量差异与比例关系并生成可视化图表。

연동 도구Excel
설치 방법 보기

이럴 때 유용합니다

  • Comparing counts for two categories
  • Visualizing category shares
  • Cleaning merged-cell data before counting
  • Exporting comparison results to Excel

포함된 파일(1)

  • SKILL.md3.6 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

categorical-comparison-analysis

This sub-skill covers one capability of the Excel workflow. For reading/counting/Parquet optimization, see the parent workflow SKILL.md.

Step1 读取文件并统计所有 sheet 的总行数,评估是否需要进行大文件优化处理。

import pandas as pd
from pandas import read_excel
from pathlib import Path

# 统计所有 sheet 的行数以决定处理策略
file_path = "input_data.xlsx"
sheet_names = pd.ExcelFile(file_path).sheet_names
total_rows = 0
for sheet in sheet_names:
    # 仅读取行索引以快速计数
    df_tmp = read_excel(file_path, sheet_name=sheet, usecols=[0])
    total_rows += len(df_tmp)

print(f"Total rows across all sheets: {total_rows}")

Step2 提取对比维度的分类信息,执行数据清洗,包括去除空值、处理合并单元格填充以及排除非数据行。

# 定义目标列名
target_col_a = "category_a_column"
target_col_b = "category_b_column"

# 处理合并单元格(ffill)并清洗数据
df[target_col_a] = df[target_col_a].ffill()
df[target_col_b] = df[target_col_b].ffill()

# 排除标题行占位符(如 '代码'、'名称')及空值
exclude_val = "代码" 
data_a = df[target_col_a].dropna()
data_a = data_a[data_a != exclude_val]

data_b = df[target_col_b].dropna()
data_b = data_b[data_b != exclude_val]

Step3 统计分类数量,计算差异值与占比,生成多维度对比统计表。

count_a = len(data_a)
count_b = len(data_b)
total_count = count_a + count_b
difference = abs(count_a - count_b)

# 计算占比
ratio_a = (count_a / total_count) * 100 if total_count > 0 else 0
ratio_b = (count_b / total_count) * 100 if total_count > 0 else 0

# 构建统计摘要
summary_df = pd.DataFrame({
    "分类名称": ["类别A", "类别B"],
    "数量": [count_a, count_b],
    "占比": [f"{ratio_a:.2f}%", f"{ratio_b:.2f}%"]
})
print(summary_df)
print(f"数量差异: {difference}")

Step4 配置中文字体并生成可视化图表(柱状图与饼图),美化输出效果。

import matplotlib.pyplot as plt

# 中文字体配置
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
labels = ['类别A', '类别B']
counts = [count_a, count_b]
colors = ['#3498db', '#e74c3c']

# 柱状图美化
bars = ax1.bar(labels, counts, color=colors, alpha=0.8, edgecolor='black')
ax1.set_title('分类数量对比', fontsize=14)
ax1.grid(axis='y', linestyle='--', alpha=0.6)
for bar in bars:
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2., height + 0.1, f'{int(height)}', 
             ha='center', va='bottom', fontweight='bold')

# 饼图美化
ax2.pie(counts, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, explode=(0.05, 0))
ax2.set_title('分类比例分布', fontsize=14)

output_img = "/mnt/data/comparison_analysis_chart.png"
plt.tight_layout()
plt.savefig(output_img, dpi=300, bbox_inches='tight')
plt.show()

Step5 将分析结果导出为 Excel 文件,并生成可供下载的链接。

from IPython.display import FileLink

output_path = "/mnt/data/analysis_report.xlsx"
with pd.ExcelWriter(output_path) as writer:
    summary_df.to_excel(writer, sheet_name='统计摘要', index=False)
    # 如果有明细数据也可在此导出

print(f"分析报告已生成")
display(FileLink(output_path, result_html_prefix="下载分析报告: "))

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Analyze Excel data using custom categories, count distributions, and compare groups with charts. Score text using its length, technical terms, numbers, and selected complex concepts, then visualize difficulty levels and the relationship between text length and scores.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Summarize Excel records using custom categories
  • Compare category distributions across groups
  • Score and grade text using adjustable rules
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

Count categories in a chosen data column after removing missing values and placeholder labels. Calculate each category’s share and create high-resolution charts combining counts, percentages, pie charts, and horizontal bars for distribution reports.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Compare record counts across categories
  • Show category shares with pie and bar charts
  • Exclude placeholder labels before counting
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

Clean category and numeric fields in structured data, compare groups with counts and cross-tabulations, and produce charts, Excel results, and a Markdown report. Export visuals as high-resolution PNG and SVG files for use in reports.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Compare category distributions across groups
  • Clean category labels and fill merged-cell gaps
  • Export analysis results to Excel
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

Filter Excel data using candidate column names, RGB color values, text prefixes, and regular expressions, which match text patterns. Calculate totals and averages, then export results to Excel with highlighted rows and a download link.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Filtering rows by RGB values or identifier prefixes
  • Converting text to numbers and calculating totals or averages
  • Extracting matching commands with their identifiers and descriptions
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

Filter rows from Excel or previously converted Parquet files, a format designed for efficient data storage. Summarize matching records by group with counts, percentages, and totals, then export the summary to Excel.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Count records containing a specified risk level by work category
  • Calculate group shares among matching records
  • Summarize large datasets already converted to Parquet
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

Find key figures in tabular data using column names or row keywords, calculate category averages and percentages, and export the results as a structured Excel report and a pie chart.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Find figures using keywords in rows
  • Calculate averages for a selected category
  • Calculate one figure as a percentage of another
OpenSenseNova/SenseNova-Skills5.9천2026년 10월 9일 업데이트

OpenSenseNova의 스킬 모두 보기

이 스킬의 문제 신고