Skip to main content
 首页 » 编程设计

python之当我有 FY 和 FQ 的字符串时创建财政年度 (FY)、财政季度 (FQ) 时间序列

2024年10月25日26Free-Thinker

我的数据框中有两个特征,分别是财政年度 (FY) 和财政季度 (FQ) 的字符串:

FY     FQ   
2008   3   
2009   4   
2009   1   
2010   2   

我使用了以下内容:

index=pd.PeriodIndex(data.FY, data.fq, freq='Q')   
data['index']=index 

我的输出如下:

index   
2008Q1   
2009Q1   
2009Q1   
2010Q1 

我期待这样的事情:

index   
2008Q3   
2009Q4   
2009Q1   
2010Q2  

请您参考如下方法:

它不起作用的原因是 PeriodIndex 期望作为描述所有所需索引的字符串列表。您可以提供必要的列表和列表理解

创建数据:

data = { 'years': ['2008', '2009', '2010', '2011'], 'Q':['3', '4', '1', '2']} 
df = pd.DataFrame(data) 
 
 
   Q years 
0  3  2008 
1  4  2009 
2  1  2010 
3  2  2011 

使用列表理解创建索引并应用它:

index = pd.PeriodIndex([y+'Q'+q for y, q in zip(df.years, df.Q)], freq='Q') 
df.index = index 
 
 
        Q years 
2008Q3  3  2008 
2009Q4  4  2009 
2010Q1  1  2010 
2011Q2  2  2011 

注意:你应该看看period_range ,使用起来更简单。