Pandas & NumPy Academy · 课时

使用 astype() 转换类型

使用 astype() 将列转换为整数、浮点数、字符串、布尔值和日期时间,并处理常见的转换错误。

第 2 / 4 课13 个步骤

使用 astype() 转换类型 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。

astype() 简介

Series.astype(dtype) 会将列从当前类型转换为您指定的类型。它会返回一个新的 Series(在完整 DataFrame 上调用时返回新的 DataFrame),而不会修改原对象。这是加载数据后修复数据类型问题的主要 Pandas 工具,可以在数值类型之间转换,也可以转换为字符串、布尔值和 Categorical 类型。

import pandas as pd

df = pd.DataFrame({'age': ['25', '30', '35']})
print('Before:', df['age'].dtype)  # object

df['age'] = df['age'].astype(int)
print('After:', df['age'].dtype)   # int64
print(df['age'] + 1)               # [26, 31, 36] — arithmetic now works

转换为数值类型

最常见的转换是将 object 转换为数值类型。您可以转换为 'int64'、'int32'、'float64'、'float32' 等类型。如果列中有任何值无法转换,astype() 会引发 ValueError。当列可能包含非数值字符串时,请改用 pd.to_numeric(series, errors='coerce');它会将错误值转换为 NaN,而不是导致程序崩溃。

import pandas as pd

df = pd.DataFrame({'price': ['10.5', '20.0', 'N/A', '30.5']})

# astype would crash on 'N/A'
# price_float = df['price'].astype(float)  # ValueError!

# pd.to_numeric with errors='coerce' is safer
df['price_float'] = pd.to_numeric(df['price'], errors='coerce')
print(df)
#   price  price_float
# 0  10.5         10.5
# 1  20.0         20.0
# 2   N/A          NaN
# 3  30.5         30.5

转换为字符串(object)

将列转换为 str(或 'object')会把每个值转换为其字符串表示形式。当您需要将数值列与文本列拼接,或希望对数值数据使用字符串方法(例如为 ID 补零)时,这非常有用。Pandas 还提供了较新的 'string' 数据类型,可为文本列提供更好的 NA 处理。

import pandas as pd

df = pd.DataFrame({'id': [1, 2, 3], 'region': ['E', 'W', 'N']})

# Concatenate id and region into a composite key
df['key'] = df['id'].astype(str) + '_' + df['region']
print(df)
#    id region  key
# 0   1      E  1_E
# 1   2      W  2_W
# 2   3      N  3_N

转换为布尔值

当列以整数(0/1)或字符串(“是”/“否”)存储 True/False 时,转换为布尔值非常有用。使用 astype(bool) 转换 0/1 整数可以直接完成:0 会变为 False,任何非零值都会变为 True。对于“是”/“否”字符串列,请先使用字典进行 map,再进行转换。

import pandas as pd

df = pd.DataFrame({
    'active_int': [1, 0, 1, 0],
    'active_str': ['Yes', 'No', 'Yes', 'No']
})

# Integer to bool
df['active_bool'] = df['active_int'].astype(bool)

# String to bool via mapping
df['active_bool2'] = df['active_str'].map({'Yes': True, 'No': False})

print(df[['active_bool', 'active_bool2']])
#    active_bool  active_bool2
# 0         True          True
# 1        False         False

缩小数值类型

默认情况下,Pandas 使用 64 位类型。如果您的整数值能放入 32 位甚至 8 位类型,就可以缩小类型,以将内存使用量减半(或降至四分之一)。请使用 pd.to_numeric(series, downcast='integer'),或通过 astype('int32') 显式转换。这是大型数据集的一项关键优化措施。

import pandas as pd
import numpy as np

df = pd.DataFrame({'count': np.random.randint(0, 200, 1_000_000)})

print('int64 bytes:', df['count'].nbytes)   # 8,000,000

df['count_int16'] = df['count'].astype('int16')  # max 32767, fits 0-200
print('int16 bytes:', df['count_int16'].nbytes)  # 2,000,000

# Or let Pandas choose the smallest type automatically
df['count_auto'] = pd.to_numeric(df['count'], downcast='integer')
print('auto dtype:', df['count_auto'].dtype)

使用 astype(dict) 转换完整 DataFrame

您可以将一个字典传给 df.astype(),一次转换多个列,其中键是列名,值是目标数据类型。这比连续为各列赋值更清晰,也能将类型转换步骤作为管道中的一个完整代码块清楚地记录下来。

import pandas as pd

df = pd.DataFrame({
    'age': ['25', '30'],
    'salary': ['50000', '70000'],
    'is_manager': ['1', '0']
})

df = df.astype({
    'age': 'int32',
    'salary': 'float64',
    'is_manager': 'bool'
})
print(df.dtypes)
# age           int32
# salary      float64
# is_manager     bool

处理 astype() 中的错误

astype() 没有内置的容错模式(不同于 pd.to_numeric)。如果转换失败,它会引发 ValueError 或 OverflowError。安全的工作流程是:(1) 先清理列(去除符号,填充 NaN),(2) 再进行转换。或者,对于数值数据使用 pd.to_numeric(errors='coerce'),也可以编写一个捕获转换错误的小型辅助函数。

import pandas as pd

# Clean then cast pattern
df = pd.DataFrame({'price': ['$1,200', '$800', '$450']})

# Step 1: remove non-numeric characters
df['price_clean'] = (
    df['price']
    .str.replace('$', '', regex=False)
    .str.replace(',', '', regex=False)
)
# Step 2: safe cast
df['price_num'] = df['price_clean'].astype(float)
print(df)
#      price price_clean  price_num
# 0  $1,200        1200     1200.0
# 1    $800         800      800.0
# 2    $450         450      450.0

转换为 Pandas StringDtype

较新的 'string' 数据类型(大写 S 的变体或 pd.StringDtype())旨在提供完善的字符串支持和正确的 NA 处理——它会将缺失字符串存储为 pd.NA,而不是 None 或 np.nan。它支持 .str 访问器,并且比 object 数据类型更好地保留 NA 语义;对于面向 Pandas 2 及更高版本的新代码,推荐使用此类型。

import pandas as pd

df = pd.DataFrame({'name': ['Alice', None, 'Carol']})

# Convert to the modern string dtype
df['name'] = df['name'].astype('string')
print(df['name'].dtype)   # string
print(df['name'].isna())  # proper NA detection
# 0    False
# 1     True
# 2    False

缩小类型时的溢出风险

将数据转换为更小的整数类型时,超出该类型范围的值会静默溢出并回绕。例如,将 300 转换为 int8(范围为 -128 到 127)会得到 44,且不会引发错误。缩小类型前,请始终确认实际数据范围适合目标类型,以避免产生隐蔽的数据损坏。

import pandas as pd
import numpy as np

df = pd.DataFrame({'value': [100, 200, 300, 127, 128]})

# int8 range: -128 to 127
df['value_i8'] = df['value'].astype('int8')
print(df)
#    value  value_i8
# 0    100       100
# 1    200       -56   <- overflow! 200-256 = -56
# 2    300        44   <- overflow! 300-256 = 44
# 3    127       127
# 4    128      -128   <- overflow!

# Always check range first
print(df['value'].max())  # 300 > 127 — int8 is UNSAFE here

使用数据类型映射验证转换结果

完成多次类型转换后,请将实际数据类型与预期映射进行比较,以验证最终模式。这种断言模式可以捕获列转换失败等错误(例如 NaN 阻止了整数转换)。请在数据加载函数末尾执行这些检查,将其作为轻量级的模式测试。

import pandas as pd

df = pd.DataFrame({
    'user_id': [1, 2, 3],
    'amount': [10.5, 20.0, 30.5],
    'active': [True, False, True]
})

expected = {'user_id': 'int64', 'amount': 'float64', 'active': 'bool'}

for col, dtype in expected.items():
    assert str(df[col].dtype) == dtype, (
        f'{col}: expected {dtype}, got {df[col].dtype}'
    )
print('Schema validation passed')

完整的转换管道示例

下面将所有内容结合起来:这是一个实际的 read_csv 后转换管道示例,它会清理格式、可靠地处理 NaN、转换为最合适的类型,并验证结果。这种“清理、转换、验证”的模式应成为每个数据导入函数的标准组成部分。

import pandas as pd

raw = pd.DataFrame({
    'user_id': ['101', '102', '103'],
    'revenue': ['$1,200', '$800', '$2,500'],
    'active': ['Yes', 'No', 'Yes']
})

df = (
    raw
    .assign(
        user_id=raw['user_id'].astype('int32'),
        revenue=pd.to_numeric(
            raw['revenue'].str.replace('[$,]', '', regex=True)
        ),
        active=raw['active'].map({'Yes': True, 'No': False})
    )
)
print(df.dtypes)
# user_id      int32
# revenue    float64
# active        bool

快速检查

测试您对使用 astype() 进行类型转换的理解。

课程回顾

本课中您学到了:astype(dtype) 会将列或整个 DataFrame 转换为新类型;对于包含非数值字符串的列,pd.to_numeric(errors='coerce') 更安全;向 astype() 传入字典可以一次转换多个列。请谨慎缩小类型以避免溢出,并始终使用断言验证最终模式。接下来,我们将探索节省内存的 Categorical 数据类型。

免费开始

用 AI 导师学习 Python — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「使用 astype() 转换类型」课时是免费的吗?

是的 — 「使用 astype() 转换类型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。

「使用 astype() 转换类型」这节课中我会学到什么?

使用 astype() 将列转换为整数、浮点数、字符串、布尔值和日期时间,并处理常见的转换错误。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Pandas & NumPy Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用 astype() 转换类型」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?

能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 检查列数据类型
  2. 使用 astype() 转换类型
  3. 分类数据类型
  4. 正确解析日期
← 返回 Pandas & NumPy Academy