2015-02-04 3 views
0

DatetimeIndex가있는 P0 월간 변경 사항이있는 S&의 66 년 시계열 DataFrame이 있습니다. 데이터를 연례 데이터 열로 분할하는 방법은 무엇입니까?Pandas의 DateTimeIndex 속성 별 색인 또는 그룹

1)

가 --Essentially 내가

c_test[c_test.index.month==1] 
c_test[c_test.index.month==2] 
c_test[c_test.index.month==3] 
c_test[c_test.index.month==4] 
....up to 12 
처럼 슬라이스하려는 루프없이 '달'과 '올해의

2) DateTimeIndex 속성) 스태킹 (라벨에 대한 유지 같은

- 'c_test.index.year'레이블로 라벨이 지정된 행

이것이 가능합니까? 또는 DateTimeIndex를 버려야합니까?

+0

을 * *는 http://stats.stackexchange.com에 더있을 수 있습니다 무엇을하고 싶으세요?/... 만약 그것이 * 어떻게 *해야한다면, 나는 당신이 원하는 출력이 무엇인지 확신 할 수 없다. : –

+0

Andy 당신이 올바른 경로로 나를 보냈습니다. 감사합니다. – Erik

답변

0

다음은 간단한 방법입니다. 년 월 일 추가 https://www.quandl.com/api/v1/datasets/GOOG/NYSE_SPY.csv

1] 데이터로드에서 예 사용하여 데이터,

import pandas as pd 
df = pd.read_csv('/Users/nicolas/Downloads/GOOG-NYSE_SPY.csv', parse_dates=[0]) 
df['Year'] = df['Date'].apply(lambda x: x.year) 
df['Month'] = df['Date'].apply(lambda x: x.month) 
df.head() 

출력 :

 Date Open High  Low Close  Volume Year Month 
0 2015-02-03 203.00 204.85 202.55 204.84 124212881 2015  2 
1 2015-02-02 200.05 202.03 197.86 201.92 163106969 2015  2 
2 2015-01-30 200.57 202.17 199.13 199.45 197729724 2015  1 
3 2015-01-29 200.38 202.30 198.68 201.99 173585424 2015  1 
4 2015-01-28 204.17 204.29 199.91 200.14 168514312 2015  1 

2] & 년 월로 그룹화하여, 매월 반환 한 계산.

month_perf = df.groupby(['Year', 'Month'])[['Close']].last() 
month_perf['month_perf'] = month_perf.pct_change(periods=1) 
month_perf = month_perf.reset_index() 
month_perf.head() 

출력 : 연간 반환 한에 대한

Year Month Close month_perf 
0 1997  8 92.59   NaN 
1 1997  9 93.31 0.007776 
2 1997  10 95.62 0.024756 
3 1997  11 94.00 -0.016942 
4 1997  12 98.09 0.043511 

3] 같은 물건, 우리는 올해 GROUPBY 것을 제외 :

GROUPBY 작업에 dataframe로 출력을 유지하기 위해 이중 [ 참고
year_perf = df.groupby(['Year'])[['Close']].last() 
year_perf['annual_perf'] = year_perf.pct_change(periods=1) 
year_perf = year_perf.reset_index() 
year_perf.head() 

출력

Year Close annual_perf 
0 1997 92.59   NaN 
1 1998 97.56  0.053678 
2 1999 123.03  0.261070 
3 2000 145.44  0.182151 
4 2001 128.81 -0.114343 

df_result = pd.merge(month_perf, year_perf, left_on='Year', right_on='Year') 
print df_result.tail() 

출력 : 17,451,515,

4] 마지막으로, 우리는 두 dataframes 병합이 약의 경우

 Year Month Close_x month_perf Close_y annual_perf 
206 2014  10 194.35 -0.031205 182.92  0.252362 
207 2014  11 201.77 0.038179 182.92  0.252362 
208 2014  12 205.76 0.019775 182.92  0.252362 
209 2015  1 205.43 -0.001604 205.43  0.123059 
210 2015  2 201.92 -0.017086 205.43  0.123059 
+0

감사합니다 이것은 매우 유용한 참조입니다. 비슷한 방법을 시도했지만 너무 좁 았기 때문에 Datbyindex를 사용하여 groupby, map 및 apply가 오류로 실행되고있었습니다. – Erik