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 祝福语2026简短对家人
16 祝福语情人节简短
17 夏天出门防晒祝福语简短
18 新娘贺词结婚祝福语简短