2016-11-10 21 views
1

我有一個表,看起來像轉換datetimeindex到QX-YY格式

Date  Open 
11/1/2016 59.970001 
10/3/2016 57.41 
9/1/2016 57.009998 
8/1/2016 56.599998 
7/1/2016 51.130001 
6/1/2016 52.439999 
5/2/2016 50 
4/1/2016 55.049999 

我只需要每季度日期行(三月,六月,九月,十二月)csv文件,並轉換日期列Q1〜 16/Q2-16/Q3-16等

代碼:

DF_sp = pd.read_csv(shareprice, index_col = 'Date', parse_dates =[0]) 
DF_Q= DF_sp.groupby(pd.TimeGrouper('Q')).nth(-1) 
DF_Q['Qx-YY'] = ???? 

回答

1

您可以使用Series.dt.to_period,然後用dt.yeardt.quarter,但首先需要轉換Index.to_series

df = df.groupby(df.Date.dt.to_period('Q')).Open.mean() 
print (df) 
Date 
2016Q2 52.496666 
2016Q3 54.913332 
2016Q4 58.690000 
Freq: Q-DEC, Name: Open, dtype: float64 

df.index = 'Q' + df.index.to_series().dt.quarter.astype(str) + '-' 
       + df.index.to_series().dt.year.astype(str).str[2:] 
print (df) 
Date 
Q2-16 52.496666 
Q3-16 54.913332 
Q4-16 58.690000 
Name: Open, dtype: float64 

另一種解決方案:

df = df.groupby(df.Date.dt.to_period('Q')).Open.mean() 
print (df) 
Date 
2016Q2 52.496666 
2016Q3 54.913332 
2016Q4 58.690000 
Freq: Q-DEC, Name: Open, dtype: float64 

y = df.index.strftime('%y') 
df.index = df.index.quarter.astype(str) 
df.index = 'Q' + df.index + '-' + y 
print (df) 
Q2-16 52.496666 
Q3-16 54.913332 
Q4-16 58.690000 
Name: Open, dtype: float64 

最好是使用period.Period.strftime - 從舊的文檔鏈接,但工作得非常好:

df = df.groupby(df.Date.dt.to_period('Q')).Open.mean() 
print (df) 
Date 
2016Q2 52.496666 
2016Q3 54.913332 
2016Q4 58.690000 
Freq: Q-DEC, Name: Open, dtype: float64 

df.index = df.index.strftime('Q%q-%y') 
print (df) 
Q2-16 52.496666 
Q3-16 54.913332 
Q4-16 58.690000 
Name: Open, dtype: float64 
+0

這不是地道的;如果你真的需要將它格式化爲一個字符串(根本不推薦),請使用.strftime和Period索引 – Jeff

+0

@Jeff - 但是如何在strftime中獲得季度?我找不到解決方案。 – jezrael

+0

http://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-span-representation – Jeff