You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中循环为每个ID生成分数计数多图?

问题描述

现有一张包含id、score1、score2、score3、score4列的表格,数据如下:

| id | score1 | score2  | score3   | score4  |
|----|--------|---------|----------|---------|
| 1  | 0.05   | 0.0608  | 0.476464 | 0.53535 |
| 1  | 0.08   | 0.0333  | 0.8263   | 0.9463  |
| 1  | 0.05   | 0.0926  | 0.8694   | 0.9903  |
| 2  | 0.08   | 0.0425  | 0.1948   | 0.3958  |
| 2  | 0.09   | 0.0992  | 0.1238   | 0.1937  |
| 4  | 0.1    | 0.0627  | 0.0738   | 0.0987  |
| 4  | 0.05   | 0.06262 | 0.721    | 0.12    |
| 4  | 0.04   | 0.05227 | 0.0825   | 0.283   |
| 4  | 0.02   | 0.04728 | 0.0628   | 0.0936  |

需求是为每个id(1、2、4)分别生成独立图表,展示4个分数的计数分布。目前通过SQL对分数分类后,只能用以下Python代码生成单图:

plt.figure(figsize=(10, 6))
sns.countplot(x='score', data=df1)
plt.xlabel('Score')
plt.xticks(rotation=90)
plt.ylabel('Count')
plt.title('Distribution per score - id 1')
plt.show()

请问有没有仅用Python循环生成所有对应图表的简便方法?

解决方案

当然可以,核心是先把宽格式数据转成适合统计的长格式,再循环遍历每个id生成图表,具体步骤如下:

1. 转换数据格式

用pandas.melt把宽表转成长表,让所有分数值集中到一列,方便后续计数统计:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 假设原始数据已加载到DataFrame df中
df_melted = df.melt(
    id_vars='id',
    value_vars=['score1', 'score2', 'score3', 'score4'],
    var_name='score_type',
    value_name='score'
)

2. 循环生成每个id的图表

遍历所有唯一id,筛选对应数据后绘制countplot:

# 获取所有不重复的id
unique_ids = df['id'].unique()

for current_id in unique_ids:
    # 筛选当前id的所有分数数据
    id_data = df_melted[df_melted['id'] == current_id]
    
    # 绘制图表
    plt.figure(figsize=(10, 6))
    sns.countplot(x='score', data=id_data)
    plt.xlabel('Score')
    plt.xticks(rotation=90)
    plt.ylabel('Count')
    plt.title(f'Distribution per score - id {current_id}')
    plt.tight_layout()  # 自动调整布局,避免标签被截断
    plt.show()

额外提示

  • 如果你的SQL已经完成了分数分类(比如把数值分成区间),直接用分类后的score列即可,无需额外处理数值
  • 要是需要保存图表,在plt.show()前添加plt.savefig(f'score_distribution_id_{current_id}.png'),就能把每个id的图表保存为单独的图片文件

内容的提问来源于stack exchange,提问作者sonia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:16:26