简体   繁体   中英

python list index out of range?

My task is to read a .csv file and take the average of the 4th columns of the data and also take the sum of the 8th data in January, which is line 13-31 from the csv file. This is my current code; it keeps telling me index out of range for line 11 and 12,how come? and as well, is there anything else wrong in my code?

file = open("citi_bike.csv", 'r')
data = []
for line in file:
  parts = line.strip().split()
  data.append(parts)

def print_detail(data):
    avg = 0
    total = 0
    for record in data:
      avg += float(record[3])
      total += float(record[7])
    avg /= len(data)
    print("\nThe following data is from " + data[0][0] + " to " + data[-1][0])
    print'\naverage miles:',(avg)
    print'\ntotal number of pass purchased:',(total)

print_detail([r for r in data if r[0].split('/')[0]=='1'])

If I understand what you've tried to do, record is an element of data, thus, record[3] and record[7] do not exist. You want to sum up the elements of the fourth and 8th columns of data not record.

I have another advice: you can use the read_csv method of the pandas library which is very powerful and fast. In one line you download the data and then use the sum function of numpy library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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