【问题标题】:How to plot a figure from a CSV file with different row如何从具有不同行的 CSV 文件中绘制图形
【发布时间】:2017-06-16 15:21:22
【问题描述】:

我想用matplotlib画一个图,读取CSV文件时总是存在错误:list index out of range,比如我的文件是这样的:

1,1,1,1,1,1
2,3,4,5,6,7
3,4,5,6
4,5,6,7
5,6
6,7

我的程序是这样的,

import csv
import matplotlib.pyplot as plt
with open('test.csv') as file:
csvreader = csv.reader(file, delimiter=',')
x1 = []
x2 = []
x3 = []
y1 = []
y2 = []
y3 = []
for row in csvreader:
    x1.append(float(row[0]))
    x2.append(float(row[2]))
    x3.append(float(row[4]))
    y1.append(float(row[1]))
    y2.append(float(row[3]))
    y3.append(float(row[5]))
  line1 = plt.plot(x1, y1, '-', linewidth=1)
  line2 = plt.plot(x2, y2, '-', linewidth=1)
  line3 = plt.plot(x3, y3, '-', linewidth=1)

【问题讨论】:

  • 您正在尝试访问循环中的 row[4] 和 row[5]。正如您自己所说,某些行可能没有这些条目(稍后甚至对于 row[2] 和 row[3])。你必须在循环中检查。
  • 另外,Python 是一种基于缩进的语言。修正你的缩进。四个空格。

标签: python csv matplotlib


【解决方案1】:

问题:如何...从...不同行的文件

计算每行值的长度并成对跳过,例如:

    csvreader = csv.reader(file, delimiter=',')
    # Define a List[3] of Dict x, y, plot
    lines = [{'x':[], 'y':[], 'plot':None} for l in range(3)]

    for values in csvreader:
        # Step over n CSV Values X,Y Pairs
        for line, i in enumerate(range(0, len(values), 2)):
            lines[line]['x'].append(float(values[i]))
            lines[line]['y'].append(float(values[i+1]))

    for line, xy in enumerate(lines,1):
        print('line{}: x:{}, y:{}'.format(line, xy['x'], xy['y']))

    for line, xy in enumerate(lines):
        lines[line]['plot'] = plt.plot(lines[line]['x'], lines[line]['y'], '-', linewidth=1)

输出

line1: x:[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], y:[1.0, 3.0, 4.0, 5.0, 6.0, 7.0]
line2: x:[1.0, 4.0, 5.0, 6.0],           y:[1.0, 5.0, 6.0, 7.0]
line3: x:[1.0, 6.0],                     y:[1.0, 7.0]

用 Python 测试:3.4.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2023-03-02
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2021-10-10
    • 2016-08-08
    • 2020-10-04
    相关资源
    最近更新 更多