python - 如何分组和绘制聚合数据?
问题描述
我的数据框中有一列包含用户登录日期,其格式如下:
0 2020-09-24 23:37:13+02:00
1 2020-09-24 22:08:02+02:00
2 2020-09-24 21:40:01+02:00
3 2020-09-24 21:16:22+02:00
4 2020-09-24 19:22:22+02:00
...
425 2020-09-07 12:55:56+02:00
426 2020-09-07 05:24:19+02:00
427 2020-09-07 05:23:17+02:00
428 2020-09-01 13:15:03+02:00
429 2020-09-01 13:10:24+02:00
Name: Login, Length: 430, dtype: datetime64[ns, Europe/Amsterdam]
我试图正确地可视化它,但我的每个解决方案都有问题。我的第一次尝试有不等长的 x-ticks(1 天与 6 天的长度相同)。
df['Login'] = df['Login'].dt.strftime('%d/%m/%y')
login_time = [login for login, df in df.groupby("Login")]
fig = plt.figure(figsize=(10, 5))
plt.plot(login_time, df.groupby(["Login"]).count())
plt.xticks(login_time, rotation = "40", ha='right', fontsize=14)
plt.ylabel("Number of logins", fontsize=20)
plt.xlabel("Date", fontsize=22)
plt.show()
更改df['Login'] = df['Login'].dt.strftime('%d/%m/%y')
为df['Login'] = df['Login'].dt.date
返回一个在无登录天数不为 0 的图。
我在想也许条形图可以很好地处理这些数据,但问题是更改plt.plot
为plt.bar
Gives ValueError: shape mismatch: objects cannot be broadcast to a single shape
,虽然我认为.count()
应该返回整数,创建 2D 投影。
我自己无法解决这个问题,我要求你帮助我并向 python noob 展示如何做得更好。非常感激!
解决方案
- 始终将日期时间列配置为一种
datetime
类型,以便正确绘制。- 将时间序列数据绘制为一种
str
类型,会导致不正确的顺序、间距和其他意想不到的烦恼。 df['Login'] = df['Login'].dt.strftime('%d/%m/%y')
将datetime
类型转换为str
类型。
- 将时间序列数据绘制为一种
- 以数据为 x 轴的条形图
datetime
具有整数索引刻度位置(例如 0、1、...、n) datetime
以数据为 x 轴的线图具有datetime
刻度位置。- 这样做
[login for login, df in df.groupby("Login")]
并plt.plot(login_time, df.groupby(["Login"]).count())
没有必要。- 使用
.groupby
并聚合所需的度量,.count
然后绘制groupby
对象。
- 使用
import pandas as pd
import matplotlib.pyplot as plt
# setup the dataframe
df = pd.DataFrame({'Login': ['2020-09-24 23:37:13+02:00', '2020-09-24 22:08:02+02:00', '2020-09-24 21:40:01+02:00', '2020-09-24 21:16:22+02:00', '2020-09-24 19:22:22+02:00 ', '2020-09-07 12:55:56+02:00', '2020-09-07 05:24:19+02:00', '2020-09-07 05:23:17+02:00', '2020-09-01 13:15:03+02:00', '2020-09-01 13:10:24+02:00']})
# convert to datetime type
df.Login = pd.to_datetime(df.Login, utc=True)
# groupby the date and count
dfg = df.groupby(df.Login.dt.date).count()
# plot the data as a barplot
ax = dfg.plot.bar(figsize=(8, 5), ylabel='Login Count', xlabel='Login Time')
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# plot a lineplot
ax = dfg.plot(marker='o', figsize=(8, 5), ylabel='Login Count', xlabel='Login Time')
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# plot a line plot on the bar plt
ax = dfg.plot.bar(figsize=(8, 5), ylabel='Login Count', xlabel='Login Time')
ax.plot(range(len(dfg.Login)), dfg.Login, color='k')
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
推荐阅读
- postgresql - Postgres connection issue EF Core / docker-compose up
- python - Dronekit-python running in docker connecting to MAVProxy on host
- python - str.contains specific pattern in pandas
- java - Spring RequestContextHolder and WebTestClient
- git - How to insert git commit date into a file being committed?
- python - 我想打印列表中的最后 10 个值
- python - 使用 Kivy,在按下按钮时动态添加项目
- react-native - 解析 json 在本机平面列表中做出反应
- discord.js - 错误:TypeError:message.guild.channels.find 不是函数
- c++ - 如何从此代码中获取递归调用的数量?