【问题标题】:Unable to access the values from the .csv file using Python3?无法使用 Python3 访问 .csv 文件中的值?
【发布时间】:2020-04-12 16:33:38
【问题描述】:

使用以下 Python3 代码,我可以访问第一列的值,但无法访问后续列。错误是:

IndexError: 列表索引超出范围

with open('smallSample.txt', 'r') as file:
    listOfLines = file.readlines()
    for line in listOfLines:
        print(line.strip())   
    header = listOfLines[0] #with all the labels
    print(header.strip().split(','))
    for row in listOfLines[1:]:
        values = row.strip().split(',')
        print(values[0]) #Able to access 1st row elements
        print(values[1]) #ERROR Unable to access the Second Column Values
        '''IndexError: list index out of range'''

存储的smallSample.txt数据为:

Date,SP500,Dividend,Earnings,Consumer Price Index,Long Interest Rate,Real Price,Real Dividend,Real Earnings,PE10

1/1/2016,1918.6,43.55,86.5,236.92,2.09,2023.23,45.93,91.22,24.21

2/1/2016,1904.42,43.72,86.47,237.11,1.78,2006.62,46.06,91.11,24

3/1/2016,2021.95,43.88,86.44,238.13,1.89,2121.32,46.04,90.69,25.37```

【问题讨论】:

  • 如果您需要我方面的任何意见,请发表评论。
  • 请修正你的错误和伴随它的散文。
  • 您是否尝试过调试并查看要拆分的内容?
  • 第 11 行输出:print(values)
  • [''] ['1/1/2016', '1918.6', '43.55', '86.5', '236.92', '2.09', '2023.23', '45.93', '91.22', '24.21'] [''] ['2/1/2016', '1904.42', '43.72', '86.47', '237.11', '1.78', '2006.62', '46.06', '91.11', '24'] [''] ['3/1/2016', '2021.95', '43.88', '86.44', '238.13', '1.89', '2121.32', '46.04', '90.69', '25.37']

标签: python python-3.x csv data-science


【解决方案1】:

实际上,您的values 不是列表。它在for 循环中一次又一次地重新初始化。使用此代码:

with open('data.txt', 'r') as file:
    listOfLines = file.readlines()
    for line in listOfLines:
        print(line.strip())   
    header = listOfLines[0] #with all the labels
    print(header.strip().split(','))
    values = []   # <= look at here
    for row in listOfLines[1:]:
        values.append(row.strip().split(',')) # <= look at here
    print(values[0])  # <= outside for loop
    print(values[1])


【讨论】:

    【解决方案2】:
    with open('SP500.txt', 'r') as file:
        lines = file.readlines()
        #for line in lines:
            #print(line)
        #header = lines[0]
        #labels = header.strip().split(',')
        #print(labels)
        listOfData = []
        totalSP = 0.0
        for line in lines[6:18]:
            values = line.strip().split(',')
            #print(values[0], values[1], values[5])
            totalSP = totalSP + float(values[1])
            listOfData.append(float(values[5]))
    
        mean_SP = totalSP/12.0
        #print(listOfData)
        max_interest = listOfData[0]
        for i in listOfData:
            if i>max_interest:
                max_interest = i
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2018-06-10
      • 2018-09-22
      • 1970-01-01
      • 2017-09-13
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多