2014-08-27 753 views

回答

2

它不工作的原因是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,使用起来更简单。

+0

谢谢!我会试试这个。 – ctan 2014-08-27 18:25:40