[英]How to find the sum of a column from a csv file using vanilla python (without using numpy or pandas)?
[英]Attempting to sum the second column of a CSV file but receiving an error. How can I correct without the use of pandas?
我嘗試了以下代碼:
此代碼有效:
import csv
#create workable file
FILENAME = "monthly_sales.csv"
#Create View Monthly Sales Modual
sales = [] #sales will be the list name
with open(FILENAME, newline="") as file:
reader = csv.reader(file)
for row in reader:
sales.append(row)
sales_list = [int(row[1]) for row in sales]
sales_list_for_sum = [int(i) for i in sales_list]
print(sales_list)
yearly_total = round(sum(sales_list),2)
list_length = len(sales_list)
monthly_average = round(yearly_total/list_length, 2)
print("Yearly Total: " + str(yearly_total))
print("Monthly Average: " + str(monthly_average))
但是當我嘗試在我的代碼中使用這個函數時,我得到以下錯誤: ValueError: invalid literal for int() with base 10: 'e'
def yearly_summary(sales):
sales_list = [int(row[1]) for row in sales]
print(sales_list)
yearly_total = round(sum(sales_list),2)
list_length = len(sales_list)
monthly_average = round(yearly_total/list_length, 2)
print("Yearly Total: " + str(yearly_total))
print("Monthly Average: " + str(monthly_average))
我確認 CSV 文件的第二列中沒有字符串“e”。
任何幫助是極大的贊賞。
首先,確保您的文字是數字而不是字符。 然后,嘗試先將文字轉換為 float,然后再轉換為 int。 所以,只要有 int() 就使用 int(float())。 有時無法直接從帶有幾位小數的字符串轉換為 int。
我同意 Matthew Barlowe。 我猜你正在閱讀標題。 沒有更多信息就很難知道。 如果您有完整的回溯來指示它發生在哪一行(我的猜測是列表理解),那將會很有幫助。 您可以嘗試查看在閱讀器旁邊添加一個是否會跳過您的標題。
next(reader)
把它放在后面
reader = csv.reader(file)
我想到了。 下面是工作代碼:
def yearly_summary(sales):
with open ("monthly_sales.csv", "r") as file:
sales = csv.reader(file)
sales_list = [int(row[1]) for row in sales]
yearly_total = round(sum(sales_list),2)
list_length = len(sales_list)
monthly_average = round(yearly_total/list_length, 2)
print("Yearly Total: " + str(yearly_total))
print("Monthly Average: " + str(monthly_average))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.