gpt4 book ai didi

python - 在一个图中组合 pandas groupby 绘制组时如何更改 x 轴

转载 作者:行者123 更新时间:2023-11-28 17:46:59 24 4
gpt4 key购买 nike

我正在处理一个聊天记录,我的数据包括时间戳、用户名和消息。我的目标是绘制多个用户每月的消息数量,以便我可以比较用户活跃的时间。

问题是 x 轴。在那里,我希望日期取决于频率(在本例中为几个月)。相反,分组数据的 Multiindex 似乎在那里输出。此外,数据似乎已正确分组,但图中每个月都有三个数据点。

我包含了一些代码来生成随机数据。 (我正在使用 Python 3.2)

这是当前输出:figure

import numpy as np
import time
import datetime
import pandas as pd
import matplotlib.pyplot as plt
from pandas.util.testing import rands

a=datetime.datetime(2012,12,3)
b=datetime.datetime(2013,12,3)
a_tstamp=time.mktime(a.timetuple())
b_tstamp=time.mktime(b.timetuple())

message_number=400
tstamps=np.random.random_integers(a_tstamp,b_tstamp,message_number)
tstamps.sort()

dates=[datetime.datetime.fromtimestamp(x) for x in tstamps]

usernames=[rands(4) for x in range(10)]
usernames=usernames*40
values=np.random.random_integers(0,45,message_number)

df=pd.DataFrame({'tstamps':dates,'usernames':usernames,'messages':[rands(5) for x in range(message_number)]})
df=df.set_index(df.tstamps)


grouped=df.groupby(df.usernames)


# trying to plot a trend to see how active user were over several months
plt.figure()
for k,g in grouped:
g=g.resample('m',how='count')
g.plot(style='*-',label=k )

plt.show()
plt.legend(loc='best')
plt.show()

最佳答案

问题:您的结果是按日期和按列(消息、用户名、tstamps)编制索引的。

2013-07-31  messages     3
tstamps 3
usernames 3
2013-08-31 messages 4
tstamps 4
usernames 4

不是对整个组重新采样,而是只取消息列,然后重新采样,

plt.figure()
for k, g in grouped:
messages = g.messages.resample('m', how='count')
messages.plot(style='*-', label=k)
plt.show()

现在绘制的系列是

2012-12-31    3
2013-01-31 3
2013-02-28 3
2013-03-31 4
...

输出看起来像

enter image description here

关于python - 在一个图中组合 pandas groupby 绘制组时如何更改 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16714069/

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