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 #CreateDataFrame 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