Python - 仅转换 Pandas DataFrame 中单个列的数据类型
pythonserver side programmingprogramming更新于 2025/11/1 18:52:17
要仅转换单个列,请使用 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
# 创建 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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

