You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas Series字符串格式时间替换失效,求排查解决方法

Pandas Series字符串替换未生效的原因及解决办法

问题场景

有一组字符串格式的时间序列,尝试用Pandas的replace方法替换开头的两位数字为一位数字,但替换未生效。

原代码

import pandas as pd
s = pd.Series(["08:05:00", "08:15:00", "08:25:00", "08:55:00", "09:05:00", "09:15:00", "09:25:00"])
print(s.dtype)
s.replace({"07:": "7:", "08:": "8:", "09:": "9:"}, inplace=True) 

当前输出

object
0    08:05:00
1    08:15:00
2    08:25:00
3    08:55:00
4    09:05:00
5    09:15:00
6    09:25:00
dtype: object

期望输出

0    8:05:00
1    8:15:00
2    8:25:00
3    8:55:00
4    9:05:00
5    9:15:00
6    9:25:00
dtype: object

问题原因

Pandas的replace方法默认是完全匹配替换,即只有当整个Series元素完全等于字典的键时才会替换。你的数据中没有元素是"08:"或"09:",都是完整的时间字符串,所以替换逻辑没有触发。

解决方法

方法一:使用str.replace做部分匹配替换

针对Series的字符串元素进行子串匹配替换,这是处理字符串部分替换的常用方式:

import pandas as pd
s = pd.Series(["08:05:00", "08:15:00", "08:25:00", "08:55:00", "09:05:00", "09:15:00", "09:25:00"])
# 用正则一次性替换所有符合规则的前缀
s = s.str.replace(r'0([789]):', r'\1:', regex=True)
print(s)

或者也可以逐个指定子串替换:

s = s.str.replace("08:", "8:").str.replace("09:", "9:").str.replace("07:", "7:")

方法二:给replace方法添加regex=True参数

开启正则模式后,replace会将字典的键当作匹配模式(支持子串或正则),对元素内的部分内容进行替换:

import pandas as pd
s = pd.Series(["08:05:00", "08:15:00", "08:25:00", "08:55:00", "09:05:00", "09:15:00", "09:25:00"])
s.replace({"08:": "8:", "09:": "9:", "07:": "7:"}, regex=True, inplace=True)
print(s)

内容的提问来源于stack exchange,提问作者Shane S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:06:17