2015-09-27 69 views
0

我有一個數據框顯示; 1)日期,價格和3)兩行價格之間的差異。創建熊貓數據框中按日期價格之間的移動摘要

dates | data | result  | change 
24-09 24  0   none 
25-09 26  2   pos 
26-09 27  1   pos 
27-09 28  1   pos 
28-09 26  -2   neg 

我想在新的數據框中創建上述數據的摘要。總結將有4列:1)開始日期,2)結束日期3)天數4)運行

例如,使用上述從25-09和27-09積極運行+4,所以我希望這樣的數據框如下所示:

在新的數據框中,對於結果值從正到負的每個變化都會有一個新行。如果run = 0,則表示沒有前一日價格的變化,並且在數據框中也需要它自己的行。

start date | end date | num days | run 
25-09  27-09  3  4   
27-09  28-09  1  -2 
23-09  24-09  1  0 

第一步,我認爲將是創建一個基於運行的值,然後顯示任何的新列「變」:「積極」,「負」或「不變」。那麼也許我可以組隊這個專欄。

回答

-1

這種風格的問題有幾個有用的函數是diff()和cumsum()。

我在示例數據中添加了一些額外的數據點以充實功能。

挑選和選擇分配給不同列的不同(和多個)聚合函數的能力是熊貓的超級特徵。

df = pd.DataFrame({'dates': ['24-09', '25-09', '26-09', '27-09', '28-09', '29-09', '30-09','01-10','02-10','03-10','04-10'], 
        'data': [24, 26, 27, 28, 26,25,30,30,30,28,25], 
        'result': [0,2,1,1,-2,0,5,0,0,-2,-3]}) 

def cat(x): 
    return 1 if x > 0 else -1 if x < 0 else 0 

df['cat'] = df['result'].map(lambda x : cat(x)) # probably there is a better way to do this 

df['change'] = df['cat'].diff() 
df['change_flag'] = df['change'].map(lambda x: 1 if x != 0 else x) 
df['change_cum_sum'] = df['change_flag'].cumsum() # which gives us our groupings 


foo = df.groupby(['change_cum_sum']).agg({'result' : np.sum,'dates' : [np.min,np.max,'count'] }) 
foo.reset_index(inplace=True) 
foo.columns = ['id','start date','end date','num days','run' ] 
print foo 

這將產生:

id start date end date num days run 
0 1  24-09 24-09   1 0 
1 2  25-09 27-09   3 4 
2 3  28-09 28-09   1 -2 
3 4  29-09 29-09   1 0 
4 5  30-09 30-09   1 5 
5 6  01-10 02-10   2 0 
6 7  03-10 04-10   2 -5 
+0

@yoshiserry - 做的解決方案爲您工作? – Dickster