簡體   English   中英

如何在不使用異常的情況下解決 ValueError dtype

[英]How Can I Solve ValueError dtype Without Using An Exception

我正在開發一個程序,該程序應該根據年齡將員工工資更新 %5 和 %10:

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("")

它起作用了,所以我的問題是為什么它只在異常情況下起作用!,有沒有辦法讓它在沒有異常的情況下完成?

由於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 自動處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM