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

使用pandas+matplotlib绘制csv数据时如何处理Frame列重复值问题

问题根因

pandas 内置的plot.line方法指定x='Frame'参数时,会默认按x轴数值排序后绘制,重复的Frame值会被放在同一个x坐标位置,不会按照csv的行顺序连接数据点,所以会出现你说的“重复值被聚合”的异常效果。

修复方案

直接调用matplotlib原生的plot方法绘制折线,用数据行的索引作为x轴坐标保证绘制顺序和csv行顺序完全一致,再将x轴的刻度标签替换为Frame列的数值即可实现需求。

修改后的完整代码
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import pandas as pd
import sys

def main(argv):
    in_csv_file = argv[0]
    print(in_csv_file)
    df = pd.read_csv(in_csv_file)
    print(df.head())
    print(df.columns.tolist())

    # 核心修改:以行索引为x轴坐标绘制,保证顺序和csv行一致
    plt.plot(df.index, df['Confidence'], color='blue')
    # 设置x轴刻度标签为Frame列的值
    # 若不需要显示重复的Frame标签,可替换为下行代码:
    # xtick_labels = df['Frame'].astype(str).where(~df['Frame'].duplicated(), '')
    xtick_labels = df['Frame']
    plt.xticks(df.index, xtick_labels)
    plt.grid(True)
    plt.xlabel('Frame')
    plt.ylabel('Confidence')

    plt.savefig('output.png', bbox_inches='tight') # bbox_inches避免标签被截断

if __name__ == '__main__':
    main(sys.argv[1:])
效果说明

运行修改后的代码,会严格按照csv的行顺序连接所有数据点,示例csv中两个Frame=9对应的0.9、0.5两个点会依次出现在x轴上,按顺序连接,完全符合预期效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:24:03