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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短