2017-07-03 89 views
-1

我正在處理時間序列數據,並且想要以連續的方式安排屬於同一月份的數據。請看代碼。在pandas-python中選擇基於日期時間索引的數據

from pandas_datareader import data as web 

from datetime import datetime 

from pandas.tseries.offsets import Day, MonthEnd 



stock= web.DataReader('AAPL',data_source='google',start='1/1/2008', 

end='12/31/2009') 

a1=stock['Close'].resample('M').apply(lambda x: x[-1]) 

a2=a1[(a1.index.month==1)] 

最後一行完成我想要的,我想知道是否有這樣做,因爲我要重複在同一行所有月份的有效方式。在此先感謝

+0

你是否想用'months'創建12個數據框? – jezrael

+0

這樣做。我更喜歡一個數據框在行中具有月份明確的值 –

+0

您可以添加數據示例嗎? – jezrael

回答

1
for month in range(12): 
    globals()['Month_%s' % str(month+1)]= a1[(a1.index.month==int(month+1))] 

這個for循環將在不同的datafr中生成所有的12個月AME的。

0

如果需要每個DataFrame分開,最好是使用dict of DataFrames:由strftime創建string小號

rng = pd.date_range('2017-04-03', periods=10, freq='20D') 
df = pd.DataFrame({'a': range(10)}, index=rng) 
print (df) 
      a 
2017-04-03 0 
2017-04-23 1 
2017-05-13 2 
2017-06-02 3 
2017-06-22 4 
2017-07-12 5 
2017-08-01 6 
2017-08-21 7 
2017-09-10 8 
2017-09-30 9 

dfs = dict(tuple(df.groupby(df.index.month))) 
print (dfs) 
{4:    a 
2017-04-03 0 
2017-04-23 1, 5:    a 
2017-05-13 2, 6:    a 
2017-06-02 3 
2017-06-22 4, 7:    a 
2017-07-12 5, 8:    a 
2017-08-01 6 
2017-08-21 7, 9:    a 
2017-09-10 8 
2017-09-30 9} 

print (dfs[4]) 
      a 
2017-04-03 0 
2017-04-23 1 

或者groupby如果需要的dict of DataFrames個月和年份鍵:

dfs = dict(tuple(df.groupby(df.index.strftime('%Y-%m')))) 
print (dfs) 
{'2017-09':    a 
2017-09-10 8 
2017-09-30 9, '2017-08':    a 
2017-08-01 6 
2017-08-21 7, '2017-06':    a 
2017-06-02 3 
2017-06-22 4, '2017-07':    a 
2017-07-12 5, '2017-05':    a 
2017-05-13 2, '2017-04':    a 
2017-04-03 0 
2017-04-23 1} 

print (dfs['2017-06']) 
      a 
2017-06-02 3 
2017-06-22 4