8
votes

Pandas Timegrouper et pivot?

C'est ce que mon Dataframe ressemble à:

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()
    ...


0 commentaires

3 Réponses :


4
votes

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


0 commentaires

5
votes

Utilisation pd.timegrouper xxx


0 commentaires

6
votes

Vous pouvez également utiliser get_dummies code> et Rééchantillon code> :

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


1 commentaires

C'est tellement plus propre que le mien. Merci!