使用pandas的infer_freq与asfreq后返回全NaN的DataFrame问题
问题分析与解决
问题根源
- 原始数据的
month列是字符串类型,直接设为索引后,pd.infer_freq()无法识别时间频率(该函数仅支持datetime64类型的索引)。 - 调用
asfreq()时,pandas自动将字符串索引转为datetime,但因频率识别错误,导致索引被错误扩展至当前系统日期(2020年8月),同时原数据的字符串索引与转换后的datetime索引无法匹配,最终interest列全为NaN。
修正后的代码
import pandas as pd # 读取数据 ice_cream_interest = pd.read_csv('ice_cream_interest.csv') # 将month列转换为datetime类型 ice_cream_interest['month'] = pd.to_datetime(ice_cream_interest['month']) # 设置datetime类型的索引 ice_cream_interest.set_index('month', inplace=True) # 正确推断频率并转换 ice_cream_interest = ice_cream_interest.asfreq(pd.infer_freq(ice_cream_interest.index))
说明
pd.to_datetime()将字符串格式的日期转为datetime64类型,确保pd.infer_freq()能正确识别月度频率('MS',即每月初)。- 转换后
asfreq()会保留原有数据,仅补充缺失的时间索引(如果有的话),不会出现全NaN的情况。
内容的提问来源于stack exchange,提问作者Max Melichov
相关产品推荐
相关产品推荐

