在Google Colab中使用PeriodIndex遇错误,需为索引分配季度时间周期
运行代码
import pandas as pd df=pd.read_csv("walmart.csv") df.head() df.set_index('Line Item',inplace=True) df.index = pd.PeriodIndex(df.index, freq='Q-JAN') df
报错信息
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/_libs/tslibs/period.pyx in pandas._libs.tslibs.period.extract_ordinals()AttributeError: 'str' object has no attribute 'ordinal'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
9 frames
ValueError: Unknown datetime string format, unable to parse: REVENUEDuring handling of the above exception, another exception occurred:
DateParseError Traceback (most recent call last)
/usr/local/lib/python3.8/dist-packages/pandas/_libs/tslibs/parsing.pyx in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso()DateParseError: Unknown datetime string format, unable to parse: REVENUE
问题原因
你把Line Item列设为索引后,尝试将其转为季度周期索引,但该列包含"REVENUE"这类非日期/季度格式的字符串,PeriodIndex无法将这类文本解析成时间周期,因此报错。
解决方法
1. 确认数据中存储季度时间的列
先检查walmart.csv,找到真正存储季度时间的列(比如列名可能是Quarter,值类似"2023Q1"、"Q4-2022"这类格式),不要用业务指标列(如Line Item)作为时间索引。
2. 正确设置季度周期索引
假设季度时间列名为Quarter,代码调整如下:
import pandas as pd df = pd.read_csv("walmart.csv") # 将季度时间列设为索引 df.set_index('Quarter', inplace=True) # 转换为季度周期索引,freq='Q-JAN'表示财年结束于1月 df.index = pd.PeriodIndex(df.index, freq='Q-JAN') df
3. 若Line Item包含季度信息但格式混乱
如果Line Item列同时包含指标名和季度信息(比如值为"REVENUE Q1 2023"),先提取其中的季度部分再转换:
import pandas as pd df = pd.read_csv("walmart.csv") # 从Line Item中提取季度字符串(示例格式:Q1 2023) df['Quarter'] = df['Line Item'].str.extract(r'(Q\d \d{4})') # 提取后将季度列设为索引并转换 df.set_index('Quarter', inplace=True) df.index = pd.PeriodIndex(df.index, freq='Q-JAN') df
内容的提问来源于stack exchange,提问作者Ratnesh Kumar

