Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

python - ValueError: invalid literal for int() with base 10: 'Height (mm)'

import csv
from decimal import *

def mean(data_set):
    return Decimal(sum(data_set)) / len(data_set)

def variance(data_set):
    mean_res = mean(data_set)
    differences = []
    squared_res = []
    for elem in data_set:
        differences.append(elem - mean_res)
    for elem in differences:
        squared_res.append(elem ** 2)
    return mean(squared_res)

def standard_deviation(data_set):
    variance_res = variance(data_set)
    return variance_res ** Decimal('0.5')

if __name__ == "__main__":
    with open("dog_data.csv", "r") as csv_file:
        csv_reader = csv.reader(csv_file)
        height_data = []
        for row in csv_reader:
            height_data.append(int(row[1]))
        print "Mean: {}".format(mean(height_data))
        print "Variance: {}".format(variance(height_data))
        print "Standard Deviation:{}".format(standard_deviation(height_data))

Here I'm getting an ValueError: invalid literal for int() with base 10: 'Height (mm)'.. What does this mean? How do i tackle this error ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think your problem is that you read the header (first line) which contain words, and you try to parse it as int.

Try to add

next(csv_reader, None)

Before your loop to skip first row.

As to "How do I tackle that error", for next time simply use print:

print row[1]

Right before the line that produced the error. See what you actually try to convert to int..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...