gpt4 book ai didi

python - 针对用户登录绘制时间序列时出现问题?

转载 作者:行者123 更新时间:2023-12-01 09:18:37 24 4
gpt4 key购买 nike

我有一个大的 pandas 数据框,它是登录网站的用户 ID 的日志:

  id        datetime
130 2018-05-17 19:46:18
133 2018-05-17 20:59:57
133 2018-05-17 21:54:01
142 2018-05-17 22:49:07
114 2018-05-17 23:02:34
136 2018-05-18 06:06:48
136 2018-05-18 12:21:38
180 2018-05-18 12:49:33
.......

120 2018-05-18 14:03:58
120 2018-05-18 15:28:36

如何将上述 pandas 数据框可视化为时间序列图?例如,我想将每个人 id 的登录频率表示为不同颜色的线(请注意,我有大约 400 个 id)。像这样的情节 (*):

[image output ]

我尝试过:

from datetime import date
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd

# set your data as df
# strip only YYYY-mm-dd part from original `datetime` column
df3.timestamp = df3.datetime.apply(lambda x: str(x)[:10])
df3.timestamp = df3.datetime.apply(lambda x: date(int(x[:4]), int(x[5:7]), int(x[8:10])))

# plot
plt.figure(figsize=(150,10))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(df3.datetime[:800], df3.id[:800], '-')
plt.gcf().autofmt_xdate()

import matplotlib.dates as dates

df5 = df3.set_index('datetime')
df5.plot(x_compat=True)
plt.gca().xaxis.set_major_locator(dates.DayLocator())

plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%d\n\n%a'))
plt.gca().invert_xaxis()
plt.gcf().autofmt_xdate(rotation=0, ha="center")
plt.figure(figsize=(150,10))

但是,我得到了这样的东西:

[image1 ]

知道如何获得类似于 (*) 的图吗?

最佳答案

我对您的示例数据进行了一些操作,以便一个用户在三天内登录。您尝试中的问题是您试图“仅绘制”登录信息。如果您想查看登录频率,则必须进行计算。因此,我读取数据并使用正确的 DateTime 索引,然后使用 groupbyresample 来计算频率。我认为对于 400 个用户,这可能会变得有点困惑,但这将绘制每个用户的每日登录情况图。

import pandas
import io

d = """id,datetime
130,2018-05-17T19:46:18
133,2018-05-17T20:59:57
133,2018-05-17T21:54:01
142,2018-05-17T22:49:07
114,2018-05-17T23:02:34
136,2018-05-18T06:06:48
136,2018-05-18T12:21:38
130,2018-05-18T12:49:33
120,2018-05-18T14:03:58
130,2018-05-19T15:28:36"""

# for the data aboce, this is a quick way to parse it
df = pandas.read_csv(io.StringIO(d), parse_dates=['datetime'], index_col='datetime')

# This method is more roundabout but is perhaps useful if you have other data
df = pandas.read_csv(io.StringIO(d))
df.datetime = pandas.to_datetime(df.datetime)
df = df.set_index('datetime')

# Plot daily logins per user id
r = df.groupby('id').resample('D').apply(len).unstack('id').plot()

Sample plot

关于python - 针对用户登录绘制时间序列时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51001858/

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