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

Python读取CSV绘图遇IndexError: list index out of range问题排查

解决CSV空格分隔数据读取的IndexError问题

问题场景

尝试用Python的matplotlib库从3列、空格分隔的CSV文件提取数据绘图,将每列存入列表时触发IndexError: list index out of range错误。

用户代码

import matplotlib.pyplot as plt
import csv

plt.grid(which='major')   
plt.xlim(140,300)
plt.ylim(0,90)
plt.ylabel(r'Altitude [km]')
plt.xlabel('Temperature [K]')

ALT = []
T = []

with open('atmoprofile.csv','r') as csvfile:
    lines = csv.reader(csvfile)
    for col in lines:
        T.append((col[0]))
        ALT.append((col[2]))

print(ALT)
print(T)

plt.plot(T,ALT, color = 'm' , marker = '.')
plt.savefig('FIG3.1.png',dpi=300)

报错信息

line 19, in <module>
    T.append((col[2]))
IndexError: list index out of range

部分CSV内容

0.0000000000000000 295.38598510303814 2.1301675254755913E-002
0.50000000000000000 293.34076715919269 1.8661556016220760E-002
1.0000000000000000 291.26698316703533 1.6456139406729336E-002
1.5000000000000000 289.15220287599828 1.4345195644685916E-002
2.0000000000000000 286.97824981214990 1.2453493432569643E-002
2.5000000000000000 284.76134910419995 1.0778799478271171E-002
3.0000000000000000 282.47997944552532 9.1857871206039686E-003
3.5000000000000000 280.14277632253931 7.8700783601433066E-003

错误原因

  1. 分隔符不匹配:csv.reader默认以逗号作为字段分隔符,但你的CSV是空格分隔,导致每一行被解析成单个元素的列表,访问col[2]自然会索引越界。
  2. 空行/不完整行:如果CSV文件末尾有空行,或者某行字段数量不足3,读取时会得到长度不足的列表,触发索引错误。

修复方案

  • 给csv.reader指定delimiter=' '(空格分隔符),同时设置skipinitialspace=True跳过字段前的空白(处理多空格分隔的情况)。
  • 增加行有效性判断,跳过空行或字段数不足3的行。
  • 将读取的字符串转换为数值类型(float),否则matplotlib会按字符串处理数据,导致绘图异常。

修复后的完整代码

import matplotlib.pyplot as plt
import csv

plt.grid(which='major')   
plt.xlim(140, 300)
plt.ylim(0, 90)
plt.ylabel(r'Altitude [km]')
plt.xlabel('Temperature [K]')

ALT = []
T = []

with open('atmoprofile.csv', 'r') as csvfile:
    # 指定空格分隔符,跳过字段前的空白
    lines = csv.reader(csvfile, delimiter=' ', skipinitialspace=True)
    for col in lines:
        # 跳过空行或字段数不足3的行
        if len(col) >= 3:
            # 转换为数值类型,注意CSV列对应关系:第一列是高度,第二列是温度
            T.append(float(col[1]))
            ALT.append(float(col[0]))

print(ALT)
print(T)

plt.plot(T, ALT, color='m', marker='.')
plt.savefig('FIG3.1.png', dpi=300)
plt.show()  # 可选:显示绘图窗口

关键说明

  • 注意CSV列对应关系:你的CSV第一列是高度(0.0、0.5等),第二列是温度(295.38等),代码中调整索引确保x轴为温度、y轴为高度,符合绘图需求。
  • 转换为float类型后,matplotlib才能正确识别数值并绘制连续曲线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:14:56