| name | excel-smart-analysis-and-cleaning |
| description | 对多 Sheet Excel 进行智能清洗、跨表核对与可视化分析。。 |
Step1 对数据进行深度清洗,包括合并单元格填充(ffill)、正则化文本处理、RGB 颜色分量转换以及异常值识别。
import re
def clean_data(df, target_col):
df[target_col] = df[target_col].ffill()
def regex_clean(text):
if not isinstance(text, str): return text
text = re.sub(r'^\d+[\.\s\-]+', '', text)
text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', text)
return text.strip()
df[target_col] = df[target_col].apply(regex_clean)
rgb_cols = ['Red', 'Green', 'Blue']
for col in rgb_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
if all(c in df.columns for c in rgb_cols):
black_mask = (df['Red'] == 0) & (df['Green'] == 0) & (df['Blue'] == 0)
df = df[black_mask]
return df
cleaned_dfs = {name: clean_data(df, 'group_col') for name, df in df_dict.items()}
Step2 执行跨表核对与多维度统计分析(如交叉分析、占比统计),并识别关键指标(如问题发现率)。
if 'Sheet1' in cleaned_dfs and 'Sheet2' in cleaned_dfs:
val1 = cleaned_dfs['Sheet1']['amount'].sum()
val2 = cleaned_dfs['Sheet2']['amount'].sum()
print(f"核对结果: Sheet1({val1}) vs Sheet2({val2}), 差异: {val1 - val2}")
target_df = pd.concat(cleaned_dfs.values(), ignore_index=True)
pivot_table = pd.crosstab(target_df['category_col'], target_df['status_col'])
pivot_table['占比'] = pivot_table.sum(axis=1) / pivot_table.sum().sum()
Step3 生成可视化图表,配置中英文字体支持,并输出带样式的 Excel 结果及下载链接。
import matplotlib.pyplot as plt
from openpyxl.styles import Font
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize=(10, 6), dpi=100)
target_df['category_col'].value_counts().plot(kind='bar', color='skyblue')
plt.title("数据分布统计")
plt.tight_layout()
plt.savefig("analysis_chart.png")
output_path = "analysis_result.xlsx"
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
target_df.to_excel(writer, index=False, sheet_name='Result')
workbook = writer.book
worksheet = writer.sheets['Result']
red_bold_font = Font(color="FF0000", bold=True)
for row in range(2, worksheet.max_row + 1):
if worksheet.cell(row=row, column=3).value > 100:
worksheet.cell(row=row, column=1).font = red_bold_font
print(f"分析完成,结果已保存至: {output_path}")