Python - 僅轉換 Pandas DataFrame 中單個列的資料型別
要僅轉換單個列,請使用 astype() 方法。讓我們首先建立一個具有 2 列的 DataFrame。其中一個是“float64”型別,另一個是“int64”−
dataFrame = pd.DataFrame( { "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "Units": [90, 120, 100, 150, 200, 130] } )
檢查型別 −
dataFrame.dtypes
假設我們需要將單個列“Units”從 int64 轉換為 int32。為此,請使用 astype() −
dataFrame.astype({'Units': 'int32'}).dtypes
示例
以下是程式碼 −
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame( { "Reg_Price": [7000.5057, 1500, 5000, 8000, 9000.75768, 6000], "Units": [90, 120, 100, 150, 200, 130] } ) print"DataFrame ...\n",dataFrame print"\nDataFrame Types ...\n",dataFrame.dtypes print"\nCast only a single column to int32..." print"\nUpdated DataFrame Types ...\n",dataFrame.astype({'Units': 'int32'}).dtypes
輸出
這將產生以下輸出 −
DataFrame ... Reg_Price Units 0 7000.50570 90 1 1500.00000 120 2 5000.00000 100 3 8000.00000 150 4 9000.75768 200 5 6000.00000 130 DataFrame Types ... Reg_Price float64 Units int64 dtype: object Cast only a single column to int32... Updated DataFrame Types ... Reg_Price float64 Units int32 dtype: object
廣告