gpt4 book ai didi

python - Pandas TimeGrouper 和 Pivot?

转载 作者:太空狗 更新时间:2023-10-29 20:44:40 25 4
gpt4 key购买 nike

这是我的数据框的样子:

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

这就是我在 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
...

我正在尝试创建 10 分钟时间间隔的 bin,以便制作条形图。并将列作为 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()
...

但我的问题是,我一辈子都弄不清楚如何按 CAT 和时间段进行分组。我最近的尝试是在执行 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)

最佳答案

您还可以使用 get_dummiesresample :

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

关于python - Pandas TimeGrouper 和 Pivot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com