Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - แปลงประเภทข้อมูลหนึ่งเป็นอีกประเภทหนึ่งใน Pandas DataFrame


ใช้วิธี astype() ใน Pandas เพื่อแปลงประเภทข้อมูลหนึ่งเป็นอีกประเภทหนึ่ง นำเข้าไลบรารีที่จำเป็น -

นำเข้าแพนด้าเป็น pd

สร้าง DataFrame ในที่นี้ เรามี 2 คอลัมน์ “Reg_Price” เป็นประเภททศนิยมและประเภท int “หน่วย” –

dataFrame =pd.DataFrame( { "Reg_Price":[7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "Units":[90, 120, 100, 150, 200, 130] })

ตรวจสอบประเภทข้อมูลของคอลัมน์ที่สร้างขึ้นด้านบน -

dataFrame.dtypes

แปลงทั้งสองประเภทเป็น int32 -

dataFrame.astype('int32').dtypes

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

นำเข้าแพนด้าเป็น pd# สร้าง DataFramedataFrame =pd.DataFrame ( { "Reg_Price":[7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "หน่วย":[90, 120, 100, 150, 200, 130 ] })print"DataFrame ...\n",dataFrameprint"\nDataFrame Types ...\n",dataFrame.dtypesprint"\nCast all columns to int32..."print"\nUpdated DataFrame Types ...\n ",dataFrame.astype('int32').dtypes

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

DataFrame ... Reg_Price Units0 7000.50570 901 1500.00000 1202 5000.00000 1003 8000.00000 1504 9000.75768 2005 600,000.000 130DataFrame Types ...Reg_Price float64Units int64dtype:objectCast all columns to int32...Updated DataFrame Types ...Reg_Price32 inttype ออบเจ็กต์:ก่อน>