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
热门推荐
5 短祝福语简短暖心
10 结婚祝福语粤语大全简短
11 晚上祝福语女生文案简短
12 法语妈妈生日祝福语简短
13 药厂开工祝福语大全简短
14 蛋糕节日祝福语简短英文
15 跨年的生日祝福语简短
16 文案祝福语英文短句简短
17 在家聚餐婚礼祝福语简短
18 学生节祝福语大全简短