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

Python2.7环境下基于测试数据绘制条形图的DataFrame构建方案

实现方案

1. 依赖准备

Python 2.7环境下需安装适配版本的依赖:

  • pandas <= 0.24.2
  • seaborn <= 0.9.1
  • matplotlib <= 2.2.5

2. 代码实现

2.1 导入依赖

# -*- coding: utf-8 -*-
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

2.2 读取并预处理数据

如果是本地csv文件,读取时将空单元格识别为空值:

# 替换为你的本地文件路径,空字符串、空格都识别为NaN
df = pd.read_csv('test_data.csv', na_values=['', ' '])

2.3 提取每行最右侧有效值

# 按优先级从高到低排列TST列(优先取最右侧的TST5)
tst_cols = ['TST5', 'TST4', 'TST3', 'TST2', 'TST1']
# 沿行向后填充,取第一个非空值即为最右侧有效值
df['latest_val'] = df[tst_cols].bfill(axis=1).iloc[:, 0]
# 过滤所有TST列均为空的无效行
df = df.dropna(subset=['latest_val'])
# 统一转为字符串类型,避免数字和字符串类型不匹配导致排序异常
df['latest_val'] = df['latest_val'].astype(str)

2.4 统计各取值出现次数

# 固定X轴刻度顺序
x_order = ['NOT_DONE', 'INCOMP', 'UNTESTED', '30', '35', '40', '45', '50']
# 按地点、取值分组统计次数
count_df = df.groupby(['PLACE', 'latest_val'], as_index=False).size().rename(columns={'size':'count'})

2.5 分地点绘制条形图

sns.set_style("whitegrid")
# 遍历四个地点分别绘图
for place in ['L1', 'L2', 'L3', 'L4']:
    plt.figure(figsize=(8, 4))
    place_df = count_df[count_df['PLACE'] == place]
    # 按指定顺序渲染X轴,无数据的刻度自动显示为0
    sns.barplot(x='latest_val', y='count', data=place_df, order=x_order, palette='Blues_d')
    plt.title(u'{} 测试结果分布'.format(place), fontsize=14)
    plt.xlabel(u'测试取值', fontsize=12)
    plt.ylabel(u'出现次数', fontsize=12)
    plt.xticks(rotation=30)
    plt.tight_layout()
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:48:01