2017-02-09 88 views
8

這是我的數據框的樣子:熊貓TimeGrouper和Pivot?

Timestamp    CAT 
0 2016-12-02 23:35:28  200 
1 2016-12-02 23:37:43  200 
2 2016-12-02 23:40:49  300 
3 2016-12-02 23:58:53  400 
4 2016-12-02 23:59:02  300 
... 

這就是我想要的熊貓做(注意時間戳進行分組):

Timestamp BINS   200 300 400 500 
2016-12-02 23:30   2  0  0  0 
2016-12-02 23:40   0  1  0  0 
2016-12-02 23:50   0  1  1  0 
... 

我試圖創造箱10分鐘的時間間隔,因此我可以製作條形圖。並且將這些列作爲CAT值,以便我可以計算每個CAT在該時間段內發生的次數。

我到目前爲止什麼可以創建時間倉:

def create_hist(df, timestamp, freq, fontsize, outfile): 
    """ Create a histogram of the number of CATs per time period.""" 

    df.set_index(timestamp,drop=False,inplace=True) 
    to_plot = df[timestamp].groupby(pandas.TimeGrouper(freq=freq)).count() 
    ... 

但我的問題是我不能爲我的生活弄清楚如何雙方貓和時間倉集團。我最新的嘗試是做GROUPBY前使用df.pivot(columns="CAT")但它只是給我的錯誤:

def create_hist(df, timestamp, freq, fontsize, outfile): 
    """ Create a histogram of the number of CATs per time period.""" 

    df.pivot(columns="CAT") 
    df.set_index(timestamp,drop=False,inplace=True) 
    to_plot = df[timestamp].groupby(pandas.TimeGrouper(freq=freq)).count() 
    ... 

這給了我:ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

回答

5

您也可以使用get_dummies d resample

In [11]: df1 = df.set_index("Timestamp") 

In [12]: pd.get_dummies(df1["CAT"]) 
Out[12]: 
        200 300 400 
Timestamp 
2016-12-02 23:35:28 1 0 0 
2016-12-02 23:37:43 1 0 0 
2016-12-02 23:40:49 0 1 0 
2016-12-02 23:58:53 0 0 1 
2016-12-02 23:59:02 0 1 0 

In [13]: pd.get_dummies(df1["CAT"]).resample("10min").sum() 
Out[13]: 
        200 300 400 
Timestamp 
2016-12-02 23:30:00 2 0 0 
2016-12-02 23:40:00 0 1 0 
2016-12-02 23:50:00 0 1 1 
+0

這比我的乾淨得多。謝謝! – andraiamatrix

4

IIUC:

In [246]: df.pivot_table(index='Timestamp', columns='CAT', aggfunc='size', fill_value=0) \ 
      .resample('10T').sum() 
Out[246]: 
CAT     200 300 400 
Timestamp 
2016-12-02 23:30:00 2 0 0 
2016-12-02 23:40:00 0 1 0 
2016-12-02 23:50:00 0 1 1 
5

使用pd.TimeGrouper

df.set_index('Timestamp') \ 
    .groupby([pd.TimeGrouper('10min'), 'CAT']) \ 
    .size().unstack(fill_value=0) 

CAT     200 300 400 
Timestamp       
2016-12-02 23:30:00 2 0 0 
2016-12-02 23:40:00 0 1 0 
2016-12-02 23:50:00 0 1 1