从基础概念到实战应用,深入剖析 convert 函数在 pandas、numpy、datetime 等模块中的核心用法、参数细节、性能差异与典型错误,助您高效完成数据转换任务。
开始学习在Python生态中,convert并非标准库中统一命名的函数,而是多模块中对“类型/格式转换”功能的统称性描述。真正用于转换的函数常以不同命名出现,如:astype、to_datetime、to_numeric、convert_dtypes、np.char.encode、datetime.strptime 等。它们共同服务于数据清洗、格式对齐、类型推断等核心任务。
| 场景 | 函数/方法 | 输入示例 | 输出示例 |
|---|---|---|---|
| 字符串→整数 | int(), pd.to_numeric |
'123' | 123 |
| 字符串→浮点 | float(), pd.to_numeric |
'3.14159' | 3.14159 |
| 时间字符串→datetime | pd.to_datetime, datetime.strptime |
'2023-12-01 15:30' | datetime(2023,12,1,15,30) |
| 数值→分类编码 | pd.Categorical |
[1,2,1,2] | Categorical([1,2,1,2], categories=[1,2]) |
| bytes→字符串 | bytes.decode() |
b'hello' | 'hello' |
| JSON字符串→dict | json.loads |
'{"a":1}' | {'a': 1} |
以下展示三类典型转换,每种均含错误处理与性能对比:
import pandas as pd
import numpy as np
from datetime import datetime
# 1. 字符串→数值:避免错误,填充缺失
data = pd.Series(['100', '200.5', 'N/A', '300'])
numeric = pd.to_numeric(data, errors='coerce') # → [100.0, 200.5, NaN, 300.0]
# 2. 多格式日期→统一datetime
dates = pd.Series(['2023/01/05', '01-15-2023', '2023-02-20'])
dt = pd.to_datetime(dates, format='mixed', dayfirst=False) # 自动识别混合格式
# 3. pandas object→原生类型(内存优化)
df = pd.DataFrame({'A': ['a','b','c'], 'B': [1,2,3]})
df_opt = df.convert_dtypes() # A→string dtype, B→Int64 dtype
| 转换方式 | 耗时(ms) | 内存(MB) | 适用场景 |
|---|---|---|---|
astype(str) |
12.3 | 1.2 | 简单类型转换 |
pd.to_numeric |
28.7 | 1.8 | 含错误处理的数值转换 |
pd.to_datetime |
85.2 | 3.5 | 日期时间解析(支持多格式) |
apply(lambda x: ...) |
320.6 | 2.1 | 自定义复杂逻辑(不推荐) |
convert_dtypes() |
18.9 | 0.9 | 整体DataFrame类型优化 |
结论:避免使用 apply 处理标量转换;优先选择向量化方法(to_numeric、to_datetime);使用 convert_dtypes 实现自动类型优化。
pandas是Python数据科学的核心库,其内置多项转换功能,常被开发者称为“convert系列函数”。这些函数高度优化,支持缺失值、时区、分类等复杂场景。
convert_dtypes():智能类型推断自pandas 1.0引入,将object列自动转换为pandas原生类型,提升性能并支持缺失值语义。
| 原始dtype | 转换后dtype | 说明 |
|---|---|---|
| object(全为整数) | Int64 | 支持NaN的整数类型 |
| object(含小数) | Float64 | 支持NaN的浮点类型 |
| object(全为字符串) | string | pandas string dtype,优于numpy string |
| object(含True/False) | boolean | 支持NA的布尔类型 |
| object(含分类值) | Categorical | 需手动调用 astype('category') |
# 示例:内存优化效果(100万行)
df = pd.DataFrame({
'id': ['ID'+str(i) for i in range(1000000)],
'value': np.random.randint(0,100, 1000000)
})
print(f'原始内存:{df.memory_usage(deep=True).sum() / 1e6:.2f} MB')
df_opt = df.convert_dtypes()
print(f'优化后内存:{df_opt.memory_usage(deep=True).sum() / 1e6:.2f} MB')
# 输出:原始:76.30 MB → 优化后:32.15 MB
astype():显式类型强制转换最常用但需谨慎使用,不处理错误值,且对缺失值敏感。
ValueErrorTypeError# 方案1:先处理缺失值
df['num'] = pd.to_numeric(df['num'], errors='coerce').astype('Int64')
# 方案2:指定dtype时避免溢出
df['small_int'] = df['id'].astype('int16') # 原id为int64但最大值<32767
pd.to_numeric():安全数值转换专为处理脏数据设计,支持三类错误策略:
errors='raise'(默认):遇到非法值立即报错errors='coerce':非法值转为NaNerrors='ignore':转换失败则返回原数据用于进一步压缩数值类型:
| 参数值 | 适用dtype | 效果 |
|---|---|---|
| 'integer' | 整数型 | 选择最小整型(int8/16/32/64) |
| 'float' | 浮点型 | 选择最小浮点型(float32/64) |
| 'signed' | 整数型 | 强制有符号整型 |
pd.to_datetime():时间解析引擎支持多格式、多输入类型、时区处理,是时间转换的核心。
format:指定格式字符串(如'%Y-%m-%d %H:%M'),提速10倍+dayfirst:处理日/月顺序歧义('01/02/2023')utc=True:统一转换为UTC时区unit='s':将整数解释为Unix时间戳(秒)# 自动识别多种格式(v1.1+)
dates = ['2023-01-01', '01/15/2023', 'Jan 20, 2023', 1672531200]
dt = pd.to_datetime(dates, format='mixed', errors='coerce')
# 输出:DatetimeIndex(['2023-01-01', '2023-01-15', '2023-01-20', '2023-01-01'], dtype='datetime64[ns]', freq=None)
某订单表含三类问题:金额为字符串、日期格式混乱、用户ID含前导零。目标:统一为标准格式以便后续分析。
# 原始数据
orders = pd.DataFrame({
'order_id': ['00123', '00456', '00789'],
'amount': ['¥199.00', '299.99元', '$350'],
'order_date': ['2023/03/12', '04-20-2023', '2023-05-01 14:30']
})
# 清洗流程
orders['order_id'] = orders['order_id'].str.zfill(5) # 补零为5位
orders['amount'] = pd.to_numeric(orders['amount'].str.extract(r'([\d.]+)', expand=False), errors='coerce')
orders['order_date'] = pd.to_datetime(orders['order_date'], format='mixed', dayfirst=False)
print(orders.dtypes)
# 输出:
# order_id string
# amount Float64
# order_date datetime64[ns]
NumPy作为底层计算库,提供高效数组转换能力,常作为pandas转换的底层支撑。
np.char系列:字符串向量化操作注意:NumPy无直接命名的convert函数,但np.char模块提供多类转换方法:
| 函数 | 功能 | 示例 |
|---|---|---|
np.char.encode |
字符串→bytes | np.char.encode(['a','b'], 'utf-8') |
np.char.decode |
bytes→字符串 | np.char.decode(b'a', 'utf-8') |
np.char.upper/lower |
大小写转换 | np.char.upper(['a','B']) → ['A','B'] |
np.char.strip |
去除首尾字符 | np.char.strip([' a ',' b ']) → ['a','b'] |
astype与tofileNumPy数组类型转换需显式调用astype,且注意内存布局:
arr = np.array([1.1, 2.9, 3.0])
# 错误:直接转int会截断而非四舍五入
int_arr = arr.astype(int) # → [1,2,3]
# 正确:先四舍五入
rounded = np.round(arr).astype(int) # → [1,3,3]
# 内存优化:转为float32
arr_f32 = arr.astype(np.float32) # 内存减半
将RGB图像数组(uint8)转换为归一化float32数组(0~1),用于模型输入:
import numpy as np
# 假设img为H×W×3的uint8数组
img = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
# 转换:uint8 → float32(0~1)
normalized = img.astype(np.float32) / 255.0
print(f'原dtype: {img.dtype}, 新dtype: {normalized.dtype}')
# → 原dtype: uint8, 新dtype: float32
# 进一步:转为NCHW格式(PyTorch要求)
nchw = np.transpose(normalized, (2, 0, 1)) # HWC → CHW
nchw = nchw[np.newaxis, ...] # → 1×3×100×100
标准库的datetime模块提供基础时间转换功能,常与pytz、dateutil配合使用。
strptime与strftime:字符串↔datetime| 格式符 | 含义 | 示例 |
|---|---|---|
| %Y | 4位年份 | 2023 |
| %m | 两位月份 | 01~12 |
| %d | 两位日期 | 01~31 |
| %H | 24小时制小时 | 00~23 |
| %M | 分钟 | 00~59 |
| %S | 秒 | 00~59 |
| %z | UTC偏移(+0800) | +0800 |
| %Z | 时区名称 | Asia/Shanghai |
from datetime import datetime
import pytz
# 输入:含时区偏移的字符串
dt_str = '2023-08-15 14:30:00+08:00'
# 解析(需%z支持)
dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S%z')
print(dt) # 2023-08-15 14:30:00+08:00
# 转换为UTC
utc_dt = dt.astimezone(pytz.UTC)
print(utc_dt) # 2023-08-15 06:30:00+00:00
# 转为本地时间(如纽约)
ny_tz = pytz.timezone('America/New_York')
ny_dt = utc_dt.astimezone(ny_tz)
print(ny_dt.strftime('%Y-%m-%d %H:%M %Z%z'))
# → 2023-08-15 02:30 EDT-0400
Unix时间戳(秒/毫秒)是系统间通用的时间表示法,转换如下:
from datetime import datetime, timezone
# 时间戳→datetime
ts = 1692102600 # 秒级
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt) # 2023-08-15 06:30:00+00:00
# datetime→时间戳
ts_new = dt.timestamp() # → 1692102600.0
# 毫秒级转换
ts_ms = 1692102600000
dt_ms = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc)
astype('int')转换含NaN的列会失败?原因:numpy int类型不支持NaN(NaN是float特有)。
解决:改用pandas的Int64(大写I)类型:
df['col'].astype('Int64') 或先用pd.to_numeric(..., errors='coerce')。
to_datetime解析日期时自动改了月份?原因:默认dayfirst=False,将'01/02/2023'解析为1月2日;若数据为日/月格式则需设dayfirst=True。
验证:使用infer_datetime_format=True或手动指定format避免歧义。
原因:float64存在浮点精度限制(如0.1+0.2≠0.3)。
解决:
• 金额类数据用Decimal类型;
• 保留小数用round(n, decimals);
• 比较时用np.isclose(a, b)。
convert_dtypes后某些列未转换?原因:convert_dtypes仅对纯类型列转换;混合类型(如['a',1])仍保留object。
解决:先用pd.to_numeric(..., errors='ignore')或fillna统一缺失值。
apply替代向量化转换 → 性能差100倍+int与Int64 → 无法存储缺失整数float(str)处理科学计数法字符串 → 可能失败astype有什么区别?pd.to_numeric的downcast参数怎么用?convert_dtypes改变数据语义?astype的本质区别许多开发者混淆二者,实则:
• astype是显式类型强制转换,要求输入与目标类型兼容,否则报错;
• convert_dtypes是智能类型推断,自动选择最优pandas原生类型,且支持缺失值。
核心差异:astype('int')要求无缺失值,而convert_dtypes可将含NaN的整数列转为Int64。
import re
from datetime import datetime
def cn_date_to_dt(s):
# 提取数字:'2023年12月1日' → ['2023','12','1']
parts = re.findall(r'\d+', s)
if len(parts) == 3:
return datetime(int(parts[0]), int(parts[1]), int(parts[2]))
return None
dates = ['2023年12月1日', '2024年1月15日', '2023年8月30日']
dt_list = [cn_date_to_dt(d) for d in dates]
print(dt_list) # [datetime(2023, 12, 1), ...]
to_numeric、to_datetime),避免applyformat,提升速度且避免歧义pd.to_numeric(..., errors='coerce')清洗数据convert_dtypes + downcastnp.isclose而非==封装常用转换逻辑,提升复用性:
def safe_convert(df, col, target_type, **kwargs):
"""安全转换列类型,自动处理缺失值"""
if target_type == 'int':
return pd.to_numeric(df[col], errors='coerce').astype('Int64')
elif target_type == 'float':
return pd.to_numeric(df[col], errors='coerce').astype('float64')
elif target_type == 'datetime':
return pd.to_datetime(df[col], errors='coerce', **kwargs)
else:
return df[col].astype(target_type)
# 使用
df['amount'] = safe_convert(df, 'amount', 'float')
df['date'] = safe_convert(df, 'date', 'datetime', format='mixed')