当前位置: 首页 > news >正文

【Pandas】pandas DataFrame astype

Pandas2.2 DataFrame

Conversion

方法描述
DataFrame.astype(dtype[, copy, errors])用于将 DataFrame 中的数据转换为指定的数据类型

pandas.DataFrame.astype

pandas.DataFrame.astype 是一个方法,用于将 DataFrame 中的数据转换为指定的数据类型。这个方法非常有用,特别是在需要将数据从一种类型转换为另一种类型时,例如将字符串转换为整数或浮点数。

方法签名
DataFrame.astype(dtype, copy=True, errors='raise')
参数说明
  • dtype: 字符串、数据类型或字典,表示要转换的数据类型。可以是单个数据类型(应用于所有列),也可以是字典(指定每列的数据类型)。
  • copy: 布尔值,默认为 True,表示是否返回一个新的 DataFrame 而不是修改原 DataFrame。
  • errors: 字符串,默认为 'raise',表示在转换过程中遇到错误时的行为。可以是 'raise'(引发错误)或 'ignore'(忽略错误)。
返回值
  • 返回一个新的 DataFrame,其中数据类型已转换。
示例

假设有一个 DataFrame 如下:

import pandas as pddata = {'A': ['1', '2', '3'],'B': ['1.1', '2.2', '3.3'],'C': ['x', 'y', 'z']
}df = pd.DataFrame(data)
print("原始 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)

输出:

原始 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A    object
B    object
C    object
dtype: object
示例1:将所有列转换为整数类型
try:df_int = df.astype(int)
except ValueError as e:print("错误信息:", e)

结果:

错误信息: invalid literal for int() with base 10: '1.1'
示例2:将指定列转换为整数类型
df['A'] = df['A'].astype(int)
print("转换后的 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)

结果:

转换后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A      int64
B    object
C    object
dtype: object
示例3:将指定列转换为不同的数据类型
df_converted = df.astype({'A': int, 'B': float, 'C': 'category'})
print("转换后的 DataFrame:")
print(df_converted)
print("\n数据类型:")
print(df_converted.dtypes)

结果:

转换后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A           int64
B         float64
C    category
dtype: object
示例4:使用 copy=False 修改原 DataFrame
df.astype({'A': int, 'B': float, 'C': 'category'}, copy=False)
print("修改后的 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)

结果:

修改后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A           int64
B         float64
C    category
dtype: object
示例5:使用 errors='ignore' 忽略转换错误
df_ignored_errors = df.astype({'A': int, 'B': float, 'C': int}, errors='ignore')
print("忽略错误后的 DataFrame:")
print(df_ignored_errors)
print("\n数据类型:")
print(df_ignored_errors.dtypes)

结果:

忽略错误后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A      int64
B    object
C    object
dtype: object

通过这些示例,可以看到 pandas.DataFrame.astype 方法如何将 DataFrame 中的数据转换为指定的数据类型。这些方法在数据预处理和类型转换时非常有用。

注意事项
  • astype 方法可以将 DataFrame 中的数据转换为指定的数据类型。
  • 可以使用单个数据类型(应用于所有列),也可以使用字典(指定每列的数据类型)。
  • 设置 copy=True 返回一个新的 DataFrame,而不会修改原 DataFrame。
  • 设置 copy=False 直接修改原 DataFrame。
  • 设置 errors='raise' 在转换过程中遇到错误时会引发错误。
  • 设置 errors='ignore' 在转换过程中遇到错误时会忽略错误。
示例代码及验证

为了验证 pandas.DataFrame.astype 方法的效果,可以运行上述示例代码并查看输出结果。

import pandas as pd# 创建一个示例 DataFrame
data = {'A': ['1', '2', '3'],'B': ['1.1', '2.2', '3.3'],'C': ['x', 'y', 'z']
}df = pd.DataFrame(data)
print("原始 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)# 尝试将所有列转换为整数类型
try:df_int = df.astype(int)
except ValueError as e:print("错误信息:", e)# 将指定列转换为整数类型
df['A'] = df['A'].astype(int)
print("\n转换后的 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)# 将指定列转换为不同的数据类型
df_converted = df.astype({'A': int, 'B': float, 'C': 'category'})
print("\n转换后的 DataFrame:")
print(df_converted)
print("\n数据类型:")
print(df_converted.dtypes)# 使用 copy=False 修改原 DataFrame
df.astype({'A': int, 'B': float, 'C': 'category'}, copy=False)
print("\n修改后的 DataFrame:")
print(df)
print("\n数据类型:")
print(df.dtypes)# 使用 errors='ignore' 忽略转换错误
df_ignored_errors = df.astype({'A': int, 'B': float, 'C': int}, errors='ignore')
print("\n忽略错误后的 DataFrame:")
print(df_ignored_errors)
print("\n数据类型:")
print(df_ignored_errors.dtypes)
运行结果

运行上述代码后,你会看到以下输出:

原始 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A    object
B    object
C    object
dtype: object
错误信息: invalid literal for int() with base 10: '1.1'转换后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A      int64
B    object
C    object
dtype: object转换后的 DataFrame:A    B   C
0  1.0  1.1 NaN
1  2.0  2.2 NaN
2  3.0  3.3 NaN数据类型:
A    float64
B    float64
C    float64
dtype: object转换后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A           int64
B         float64
C    category
dtype: object修改后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A           int64
B         float64
C    category
dtype: object忽略错误后的 DataFrame:A    B  C
0  1  1.1  x
1  2  2.2  y
2  3  3.3  z数据类型:
A      int64
B    object
C    object
dtype: object

通过这些示例,可以看到 pandas.DataFrame.astype 方法如何将 DataFrame 中的数据转换为指定的数据类型。这些方法在数据预处理和类型转换时非常有用。


http://www.mrgr.cn/news/97464.html

相关文章:

  • 4月7日随笔
  • 内网文件传输新体验,聊天、传输、自定义,一应俱全
  • C++中常用的十大排序方法之4——希尔排序
  • Redlinux(2025.3.29)
  • rhcsa第三次作业
  • 手搓多模态-06 数据预处理
  • 操作系统概述(3)
  • nginx管理nacos集群地址
  • 剖析AI与5G:是夸大其词,还是时代变革的引擎?-优雅草卓伊凡
  • CMake实战指南一:add_custom_command
  • Linux学习笔记(2) 命令基础:从概念到实践(期末,期中复习笔记全)
  • Redis 的五种数据类型面试回答
  • 使用成员函数指针数组简化C++类中的操作
  • 计算机系统---性能指标(3)续航与散热
  • 基于大模型的GCSE预测与治疗优化系统技术方案
  • NVIDIA Jetson 环境安装指导 PyTorch | Conda | cudnn | docker
  • 面试题vue
  • Ubuntu 22 Linux上部署DeepSeek R1保姆式操作详解(Xinference方式)
  • AI Agent设计模式一:Chain
  • vue2拖拉拽做个模拟公式工具