and*_*rix 8 python pivot histogram pandas pandas-groupby
这就是我的数据框架:
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
...
Run Code Online (Sandbox Code Playgroud)
这就是我在Pandas中要做的事情(请注意时间戳已分组):
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
...
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建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()
...
Run Code Online (Sandbox Code Playgroud)
但我的问题是我不能为我的生活弄清楚如何按CAT和时间箱分组.我最近的尝试是df.pivot(columns="CAT")在进行groupby之前使用,但它只是给了我错误:
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()
...
Run Code Online (Sandbox Code Playgroud)
这给了我: ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
运用 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
Run Code Online (Sandbox Code Playgroud)
您还可以使用get_dummies和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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |