【问题标题】:IndexError when trying to read y variable into pyplot.scatter尝试将 y 变量读入 pyplot.scatter 时出现 IndexError
【发布时间】:2019-01-13 17:42:15
【问题描述】:

我正在尝试创建的最终产品是一个程序,该程序从 csv(附加,称为 OutputC.csv)获取输入,并允许用户从他们选择的列中绘制散点图。我决定首先创建预选列的图形,然后再使用 rawinput 和变量。因此,我遇到的问题是 python 将数据读取到 pyplot 中的方式。数据取自输入 csv 并写入它自己的文件(Qout14.csv),我试图从中绘制。不幸的是,即使 x 和 y 变量列表的长度相同,我也会收到 IndexError。在做了一些阅读后,我想知道问题是否可能是 y 数据没有逗号分隔实例中的数据,因此它可能只是将所有 y 作为字符串读取,因此它没有任何其他内容名单。令人困惑的部分是同一行代码适用于变量的另一侧,即 x。谁能指出我的错误可能在哪里?

Example of Inputs(Columns 1 and 7 of OutputC.csv):
pcp Qout14
2.3 7.20E-03
3   1.34E-02
3.3 1.50E-02
2.3 8.25E-03
3   1.32E-02
2.5 9.47E-03
3   1.28E-02
3.6 1.81E-02
2.5 1.02E-02
2.5 9.44E-03
2   6.00E-03
2.8 1.17E-02
2.8 1.12E-02
2.8 1.16E-02

Traceback(最近一次调用最后一次):文件 “C:\Users\jmiyama\Desktop\Python Files\OutputCtoScatterplot.py”,行 48,在 main() 文件“C:\Users\jmiyama\Desktop\Python Files\OutputCtoScatterplot.py”,第 35 行,在 main y = [row.split(',')[1] for row in data[1:]] IndexError: list index out of range

import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas
import collections

def getColumn(filename, column):
    results = csv.reader(open(filename), dialect='excel')   
    return [result[column] for result in results]

def dictcolumn():
    pcp = getColumn("C:\\Users\\jmiyama\\Desktop\\Python Files\\OutputC.csv",1)
    Qout14 = getColumn("C:\\Users\\jmiyama\\Desktop\\Python Files\\OutputC.csv",7)
    scatter={}
    scatter["pcp"]= pcp
    scatter["Qout14"]= Qout14
    return scatter

def main():
    scatter = dictcolumn()
    file = 'Qout14.csv'
    with open(file, 'w+') as csv_file:
        writer = csv.writer(csv_file, lineterminator='\n')
        writer.writerows(zip(*scatter.values()))

    with open("Qout14.csv") as f:
        data = f.read()
    data = data.split('\n')
    # trying to split the zipped values into columns
    x = [row.split(',')[0] for row in data[1:]]
    #THE CODE WORKS UP TO HERE
    y = [row.split(',')[1] for row in data[1:]]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.grid()

    plt.scatter(x,y)
    plt.xlabel('pcp')
    plt.ylabel('Qout14')
    plt.title('Qout14 vs pcp')
    plt.show()

if __name__ == '__main__':
   main()

【问题讨论】:

    标签: python pandas csv matplotlib index-error


    【解决方案1】:

    data = data.split('\n') 似乎在末尾添加了额外的“空白”行,所以下面会起作用。

    x = [row.split(',')[0] for row in data[1:-1]]
    y = [row.split(',')[1] for row in data[1:-1]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 2021-01-03
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多