Python绘制CSV文件时如何自动识别并跳过开头非数据行?
自动识别CSV数据起始行的解决方法
针对你遇到的CSV开头包含大量设备信息、需要自动定位数据起始行的问题,这里提供两种实用思路和修改后的代码:
方法一:通过数据格式自动识别
核心逻辑:遍历每一行,尝试将首列转换为浮点数(你的数据首列是时间,属于数字类型),能成功转换的行即为数据起始行,之后开始读取数据。
修改后的代码:
import matplotlib.pyplot as plt import csv a = [] b = [] c = [] d = [] e = [] with open('PATH','r') as csvfile: lines = csv.reader(csvfile, delimiter=',') data_started = False for row in lines: # 跳过空行 if not row: continue # 尝试转换首列,判断是否为数据行 try: float(row[0]) data_started = True except ValueError: # 未找到数据行前,跳过非数据内容 if not data_started: continue # 开始读取有效数据 if data_started: a.append(float(row[0])) b.append(float(row[1])) # c.append(float(row[2])) # d.append(float(row[3])) # e.append(float(row[4])) f = plt.figure() f.set_figwidth(12) f.set_figheight(8) plt.plot(a, b, linewidth=0.35, color = 'b', label = "Sensor 1") # plt.plot(a, c, linewidth=0.35, color = 'g', label = "Sensor 2") plt.title('Pressure Report', fontsize = 20) plt.xlabel('Time(s)') plt.ylabel('Pressure(bar)') plt.grid() plt.legend() plt.show()
方法二:通过表头精准定位
如果你明确知道数据行的表头内容(比如表头是Time(s)、Pressure(bar)),可以先找到表头所在行,从下一行开始读取数据,这种方法精准度更高:
修改后的代码示例:
import matplotlib.pyplot as plt import csv a = [] b = [] c = [] d = [] e = [] # 根据实际情况定义目标表头 target_header = ['Time(s)', 'Pressure(bar)'] with open('PATH','r') as csvfile: lines = csv.reader(csvfile, delimiter=',') data_started = False for row in lines: # 跳过空行 if not row: continue # 匹配到目标表头后,标记开始读取数据 if row[:2] == target_header: data_started = True continue # 读取有效数据 if data_started: a.append(float(row[0])) b.append(float(row[1])) # c.append(float(row[2])) # d.append(float(row[3])) # e.append(float(row[4])) f = plt.figure() f.set_figwidth(12) f.set_figheight(8) plt.plot(a, b, linewidth=0.35, color = 'b', label = "Sensor 1") # plt.plot(a, c, linewidth=0.35, color = 'g', label = "Sensor 2") plt.title('Pressure Report', fontsize = 20) plt.xlabel('Time(s)') plt.ylabel('Pressure(bar)') plt.grid() plt.legend() plt.show()
注意事项
- 方法一适合表头不固定,但数据列均为数字的场景;方法二适合表头固定、需要精准匹配的场景。
- 若CSV中混有少量注释行,方法一会自动跳过非数字开头的行,保证只读取有效数据。
内容的提问来源于stack exchange,提问作者Georgius
相关产品推荐
相关产品推荐

