วิธีแก้ไข: valueerror: ไม่สามารถแปลง float nan เป็น int
ข้อผิดพลาดที่คุณอาจพบเมื่อใช้นุ่นคือ:
ValueError : cannot convert float NaN to integer
ข้อผิดพลาดนี้เกิดขึ้นเมื่อคุณพยายามแปลงคอลัมน์ใน DataFrame ของ pandas จากทศนิยมเป็นจำนวนเต็ม เมื่อคอลัมน์มีค่า NaN
ตัวอย่างต่อไปนี้แสดงวิธีการแก้ไขข้อผิดพลาดนี้ในทางปฏิบัติ
วิธีการทำซ้ำข้อผิดพลาด
สมมติว่าเราสร้าง DataFrame แพนด้าต่อไปนี้:
import pandas as pd import numpy as np #createDataFrame df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, np. no , 10, 6, 5, np. no , 9, 12]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 NaN 2 15 7 10 3 14 9 6 4 19 12 5 5 23 9 NaN 6 25 9 9 7 29 4 12
ปัจจุบัน คอลัมน์ “การตีกลับ” อยู่ในประเภทข้อมูล “ลอย”
#print data type of 'rebounds' column df[' rebounds ']. dtype dtype('float64')
สมมติว่าเรากำลังพยายามแปลงคอลัมน์ “ตีกลับ” จากทศนิยมเป็นจำนวนเต็ม:
#attempt to convert 'rebounds' column from float to integer df[' rebounds '] = df[' rebounds ']. astype (int) ValueError : cannot convert float NaN to integer
เราได้รับ ValueError เนื่องจากค่า NaN ในคอลัมน์ “ตีกลับ” ไม่สามารถแปลงเป็นค่าจำนวนเต็มได้
วิธีการแก้ไขข้อผิดพลาด
วิธีแก้ไขข้อผิดพลาดนี้คือการจัดการค่า NaN ก่อนที่จะพยายามแปลงคอลัมน์จากทศนิยมเป็นจำนวนเต็ม
เราสามารถใช้โค้ดต่อไปนี้เพื่อระบุแถวที่มีค่า NaN ก่อน:
#print rows in DataFrame that contain NaN in 'rebounds' column print (df[df[' rebounds ']. isnull ()]) points assists rebounds 1 12 7 NaN 5 23 9 NaN
จากนั้นเราสามารถลบแถวที่มีค่า NaN หรือแทนที่ค่า NaN ด้วยค่าอื่นก่อนที่จะแปลงคอลัมน์จากทศนิยมเป็นจำนวนเต็ม:
วิธีที่ 1: ลบแถวที่มีค่า NaN
#drop all rows with NaN values df = df. dropna () #convert 'rebounds' column from float to integer df[' rebounds '] = df[' rebounds ']. astype (int) #view updated DataFrame df points assists rebounds 0 25 5 11 2 15 7 10 3 14 9 6 4 19 12 5 6 25 9 9 7 29 4 12 #view class of 'rebounds' column df[' rebounds ']. dtype dtype('int64')
วิธีที่ 2: แทนที่ค่า NaN
#replace all NaN values with zeros df[' rebounds '] = df[' rebounds ']. fillna ( 0 ) #convert 'rebounds' column from float to integer df[' rebounds '] = df[' rebounds ']. astype (int) #view updated DataFrame df points assists rebounds 0 25 5 11 1 12 7 0 2 15 7 10 3 14 9 6 4 19 12 5 5 23 9 0 6 25 9 9 7 29 4 12 #view class of 'rebounds' column df[' rebounds ']. dtype dtype('int64')
โปรดทราบว่าทั้งสองวิธีช่วยให้เราหลีกเลี่ยง ValueError และแปลงคอลัมน์ float เป็นคอลัมน์จำนวนเต็มได้สำเร็จ
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีแก้ไขข้อผิดพลาดทั่วไปอื่นๆ ใน Python:
วิธีแก้ไข: คอลัมน์ซ้อนทับกันแต่ไม่ได้ระบุส่วนต่อท้าย
วิธีแก้ไข: วัตถุ ‘numpy.ndarray’ ไม่มีแอตทริบิวต์ ‘ผนวก’
วิธีแก้ไข: หากใช้ค่าสเกลาร์ทั้งหมด คุณจะต้องผ่านดัชนี