首页 > 解决方案 > 如何分组和绘制聚合数据?

问题描述

我的数据框中有一列包含用户登录日期,其格式如下:

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()

情节 1

更改df['Login'] = df['Login'].dt.strftime('%d/%m/%y')df['Login'] = df['Login'].dt.date返回一个在无登录天数不为 0 的图。

情节 2

我在想也许条形图可以很好地处理这些数据,但问题是更改plt.plotplt.barGives ValueError: shape mismatch: objects cannot be broadcast to a single shape,虽然我认为.count()应该返回整数,创建 2D 投影。

我自己无法解决这个问题,我要求你帮助我并向 python noob 展示如何做得更好。非常感激!

标签: pythonpandasmatplotlibdatetime64

解决方案


  • 始终将日期时间列配置为一种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')

在此处输入图像描述


推荐阅读