简体   繁体   English

试图从 CSV 文件中读取数据,列表索引超出范围?

[英]Trying to read in data from a CSV file, list index out of range?

I have no idea why this isn't working, I've done this before with CSV files and it worked.我不知道为什么这不起作用,我以前用 CSV 文件做过这个并且它起作用了。 The file has no blank lines or blank values and the data is separated by commas.该文件没有空行或空值,数据以逗号分隔。 This is what I have:这就是我所拥有的:

#Create empty lists for data.
Date = []
Open = []
High = []
Low = []
Close = []
Adj_Close = []
Volume = []

#Fill lists with data.
with open("AAPL_train.csv", "r") as infile:
    for lines in infile:
        lines = lines.split(",")
        Date.append(lines[0])
        Open.append(lines[1])
        High.append(lines[2])
        Low.append(lines[3])
        Close.append(lines[4])
        Adj_Close.append(lines[5])
        Volume.append(lines[6])

My error code is reading that it goes out of index at the Open.append(lines[1]) line.我的错误代码显示它在Open.append(lines[1])行中超出索引。

Then here is a sample of the data to show you what it looks like.然后这里是一个数据样本,向您展示它的样子。

Any ideas?有任何想法吗? Thank you.谢谢你。

Edited to add: The error I'm getting is IndexError: list index out of range on line 18, and when I try to do a print line after each loop, I get nothing but the error.编辑添加:我得到的错误是 IndexError: list index out of range on line 18,当我尝试在每个循环之后执行打印行时,除了错误之外什么也没有。

import csv

#Create empty lists for data.
Date = []
Open = []
High = []
Low = []
Close = []
Adj_Close = []
Volume = []

#Fill lists with data.
with open("AAPL_train.csv", "r") as infile:
    csv_reader = csv.reader(infile, delimiter=','):
        # skip header
        next(csv_reader)
        for row in infile:
            Date.append(row[0])
            Open.append(row[1])
            High.append(row[2])
            Low.append(row[3])
            Close.append(row[4])
            Adj_Close.append(row[5])
            Volume.append(row[6])

I've updated your code to use the inbuilt python csv package.我已更新您的代码以使用内置的 python csv package。 It makes life easier when dealing with CSV and its generator should help prevent any memory problems down the line!在处理 CSV 时,它让生活更轻松,它的生成器应该有助于防止任何 memory 问题!

I also added the next(csv_reader) call in order to skip the header in your csv data.我还添加了next(csv_reader)调用以跳过 csv 数据中的 header。 I made the assumption this was data you may not actually want to record.我假设这是您可能实际上不想记录的数据。

Try using pandas:尝试使用 pandas:

import pandas as pd

df = pd.read_csv(AAPL_train.csv)

Date = df['Date'].tolist()
Open = df['Open'].tolist()
High = df['High'].tolist()
Low = df['Low'].tolist()
Close = df['Close'].tolist()
Adj_Close = df['Adj_Close'].tolist()
Volume = df['Volume'].tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM