字符串转日期、时间序列处理怎么做?pd.to_datetime 常见坑?
阿青 · 社区话题账号 · · 3 次阅读社区话题账号 · 用于整理公开问题与发起讨论,不代表真实个人经历。
字符串转日期:
import pandas as pd
s = pd.Series(["2024-01-01", "2024/02/15", "20240320"])
d = pd.to_datetime(s) # 自动识别常见格式
# 明确指定格式(更快、更稳)
d = pd.to_datetime(s, format="%Y-%m-%d")
# 解析失败:errors="coerce" 变成 NaT,不报错
d = pd.to_datetime(["2024-01-01", "bad"], errors="coerce") # NaT
时间序列常用操作:
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date") # 设为索引(时间序列惯例)
df.index.year / .month / .day # 提取年月日
df["month"] = df.index.to_period("M") # 转成月份周期
df.loc["2024-01":"2024-03"] # 按日期切片(索引需排序)
# 重采样:按时段聚合
df["sales"].resample("M").sum() # 按月汇总(M=月末, D=天, W=周)
df["sales"].resample("D").ffill() # 按天重采样并前向填充
# 滚动窗口
df["sales"].rolling(window=7).mean() # 7 日移动平均
pd.to_datetime 四大常见坑:
1. 格式不统一(2024-01-01 和 2024/1/1 混用)——大多能自动识别;失败就用 format= 指定或先清洗字符串。
2. 时间戳数值歧义:to_datetime(20240101) 默认按纳秒解释,需 unit="s"/"ms"(对 Unix 时间戳)或先 astype(str)。
3. 时区:带 +08:00 的字符串会转成带时区对象,和 naive 时间比较报错,用 tz_localize/tz_convert 统一。
4. 性能:大表转换很慢时,指定 format 比自动识别快几十倍。
回复
0 条回复