我正在開發一個程式,該程式應該根據年齡將員工工資更新 %5 和 :
import csv
infile = open('employee.csv')
csvreader = csv.reader(infile)
rows = []
for row in csvreader:
rows.append(row)
for i in rows:
if(int(i[2]) < 40): #LINE CAUSING A PROBLEM
i[3] = round((1.05 * float(i[3])) , 2)
else:
i[3] = round((1.10 * float(i[3])) , 2)
print('\n\nList after updation:')
#loop print the data on the compile
for row in rows:
print(row)
#open file and write the updated data
with open('employeeUpdate.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
當我運行它時,我收到以下錯誤:
ValueError Traceback (most recent call last)
---> 23 if(int(i[2]) < 40):
ValueError: invalid literal for int() with base 10: 'age'
資料樣本:
ID employee name age salary
1 Sara Wales 33 60994
2 John Smith 42 78399
3 Michael Ousley 22 58000
4 Rami Elliot 50 88382
我仔細檢查了資料型別,它是一個整數-->('age', dtype('int64'))
我嘗試with open ('employee.csv', r) as infile將問題行更改為,if int(float(i[2]) < 40):但它們都不起作用。它說不能將字串轉換為浮點數。我不知道為什么它將整數作為字串讀取。
但是當我添加這樣的例外時:
for i in rows:
try:
if (int(i[2]) < 40):
i[3] = round((1.05 * int(i[3])) , 2)
else:
i[3] = round((1.10 * int(i[3])) , 2)
except ValueError:
print("")
它起作用了,所以我的問題是為什么它只在例外情況下起作用!,有沒有辦法讓它在沒有例外的情況下完成?
uj5u.com熱心網友回復:
由于csv.reader()連續讀取流直到 EOF,因此它沒有標題行的概念。對于 的第一次迭代rows,i將始終是字串標題行。并且您正在嘗試將文本“age”轉換為 int,這會使 Python 出錯。
您的 try-except 有效,因為它只是掩蓋了從第一行引發的錯誤并列印了一個空行。
要修復它,只需從檔案中跳過一行以不包含標題行,或者在進行 int 轉換時跳過第一次迭代。
with open('employee.csv') as infile:
infile.readline()
csvreader = csv.reader(infile)
# do stuff with csvreader
在處理大型資料集和進行復雜的資料操作時,請考慮使用 pandas 庫。此處描述的問題和 dtype 轉換將由 Pandas 自動處理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350285.html
上一篇:Python正則運算式提取分和秒
