2017-09-20 46 views
3

我有一分鐘間隔的市場營銷數據。 爲CSV-表的一個樣本,每一行代表爲每分鐘最大值:查找pd.DateFrame中每5行的最大值

time ch1  ch2 ch3 ch4  
20:03 1754 539 149 1337  
20:04 2073 576 160 1448  
20:05 2246 599 176 1515  
20:06 2246 637 176 1531  
20:07 2457 651 183 1549  
20:08 2564 677 184 1655  
20:09 2624 712 191 1699  
20:10 2742 717 194 1672  
20:11 2788 714 199 1675  
20:12 2792 693 186 1680  
20:13 2914 708 188 1672  
20:14 3067 715 194 1685  
20:15 3067 725 196 1682  

另外,我需要找到最大值,每次5分鐘。因此,我需要爲每列的每5行(或更少 - 如果沒有更多行保留)找到最大值並將其插入新的5分鐘行。

我希望收到(爲例):

每個新行都有代表5

time ch1  ch2 ch3 ch4  
20:03 2564 677 184 1655  
20:08 2914 717 199 1699  
20:13 3067 725 196 1685  

老實說,我已經搜查,但沒有結果最大值。

有沒有在Python中爲我的任務提供一些優雅的解決方案? 感謝您的幫助!

回答

3
g = df.groupby(np.arange(len(df)) // 5) 
g.max().assign(time=g.time.first()) 

    time ch1 ch2 ch3 ch4 ch5 
0 20:03 2457 651 183 1549 4840 
1 20:08 2792 717 199 1699 5376 
2 20:13 3067 725 196 1685 5670 
4

通過使用您的輸入:

df['group']=df.index//5 
target=df.groupby('group').agg(max) 
target['time']=df.groupby('group').time.agg(min) 

Out[511]: 
     time ch1 ch2 ch3 ch4 ch5 
group         
0  20:03 2457 651 183 1549 4840 
1  20:08 2792 717 199 1699 5376 
2  20:13 3067 725 196 1685 5670 
3

我要去假設你沒有,因爲你指定的,這是數據的CSV表的值轉換爲datetime,所以我會在指數轉換成datetime。現在

df.index = pd.to_datetime(df.time,format='%H:%M') 

,該指數是datetime格式,我們可以5個分鐘爲間隔使用resample到組。注:我將設定基地3在這裏,因爲這是你怎麼想它格式化,但我認爲,從長遠來看,你可能更適合留在0,所以對數據進行分組只需要運行

df.resample('5T',base=3).max().drop('time',1) 

在底座動態設置的第一分鐘值使用

df.resample('5T',base=int(df.time.values[0][-1:])).max().drop('time',1) 

息率

     ch1 ch2 ch3 ch4 
time 
2017-09-20 20:03:00 2457 651 183 1549 
2017-09-20 20:08:00 2792 717 199 1699 
2017-09-20 20:13:00 3067 725 196 1685 

如果你不希望在指數的日期只運行

df.index = df.index.time 

但是,需要包括日期重新採樣

  ch1 ch2 ch3 ch4 
20:03:00 2457 651 183 1549 
20:08:00 2792 717 199 1699 
20:13:00 3067 725 196 1685 
+0

謝謝!但在數據集中有幾天(15.09,16.09,17.09)。你現在,如何設定不同日期的日期? (因爲它會是.xls格式,而不僅僅是.csv)。 – Gregof

+0

您是否可以更新您的樣本以包含日期?如果它只是一列日期,則可以合併列並將其設置爲日期時間對象 – DJK