2016-09-22 28 views
0

我正在使用Pandas來構造和處理數據。 這是我的數據框:循環組Pandas Dataframe並獲取總數/計數

DataFrame

這是使我能夠得到這個數據幀代碼:

(data[['time_bucket', 'beginning_time', 'bitrate', 2, 3]].groupby(['time_bucket', 'beginning_time', 2, 3])).aggregate(np.mean) 

現在我想有總和(理想情況下,總和與計數)我的'比特率'分組在同一個time_bucket中。例如,對於第一個time_bucket((2016-07-08 02:00:00,2016-07-08 02:05:00)),所有情況下的「比特率」必須爲93750000,總數爲25,計數爲25, 。

我這樣做:

data[['time_bucket', 'bitrate']].groupby(['time_bucket']).agg(['sum', 'count']) 

這是結果:

enter image description here

但我真的希望有一個數據幀我的所有數據

我可以。做一個簡單的l超過'time_bucket'並應用計算所有比特率之和的函數? 任何想法?謝謝 !

+0

請提供一個小的代碼片段,提供您的問題所需的數據框(或它們的一個小近似值)。這些圖像不能加載到Python中。 –

回答

1

我認爲你需要merge,但需要DataFramesindexes相同的水平,所以使用reset_index。最後得到原Multiindex通過set_index

data = pd.DataFrame({'A':[1,1,1,1,1,1], 
        'B':[4,4,4,5,5,5], 
        'C':[3,3,3,1,1,1], 
        'D':[1,3,1,3,1,3], 
        'E':[5,3,6,5,7,1]}) 

print (data) 
    A B C D E 
0 1 4 3 1 5 
1 1 4 3 3 3 
2 1 4 3 1 6 
3 1 5 1 3 5 
4 1 5 1 1 7 
5 1 5 1 3 1 
df1 = data[['A', 'B', 'C', 'D','E']].groupby(['A', 'B', 'C', 'D']).aggregate(np.mean) 
print (df1) 
      E 
A B C D  
1 4 3 1 5.5 
     3 3.0 
    5 1 1 7.0 
     3 3.0 

df2 = data[['A', 'C']].groupby(['A'])['C'].agg(['sum', 'count']) 
print (df2) 
    sum count 
A    
1 12  6 

print (pd.merge(df1.reset_index(['B','C','D']), df2, left_index=True, right_index=True) 
     .set_index(['B','C','D'], append=True)) 

      E sum count 
A B C D     
1 4 3 1 5.5 12  6 
     3 3.0 12  6 
    5 1 1 7.0 12  6 
     3 3.0 12  6 

我嘗試另一種解決方案,從df1得到輸出,但這種聚集所以不可能得到正確的數據。如果總和水平爲C,則會得到8而不是12

+0

你能幫我做這個嗎? :) http://stackoverflow.com/questions/39691671/resampling-timeseries-with-a-given-timedelta – DataAddicted

+0

是的,請參閱我的解決方案。 – jezrael