首页 > 解决方案 > 无法使用 Seaborn 绘图

问题描述

您好我的数据集如下

username    switch_state    time    
abcd         sw-off         07:53:15 +05:00 
abcd         sw-on          07:53:15 +05:00

现在使用这个我需要找到在给定的一天一天中有多少次开关状态被操纵,即打开或关闭。我的测试代码如下

switch_off=df.loc[df['switch_state']=='sw-off']#only off switches
groupy_result=switch_off.groupby(['time','username']).count()['switch_state'].unstack#grouping the data on the base of time and username and finding the count on a given day. fair enough

该 groupby 子句的结果为

print(groupy_result)
username  abcd
time             
05:08:35        3
07:53:15        3
07:58:40        1

现在您可以看到计数在时间列中连接。我需要将它们分开,以便我可以使用 Seaborn 散点图绘制它。我需要有 x 和 y 值,在我的情况下将是 x=time,y=count 请帮助我如何绘制此列。

`

标签: pythonpandasseabornscatter-plotpandas-groupby

解决方案


您可以尝试以下方法来获取数据DataFrame本身

df = df.loc[df['switch_state']=='sw-off']
df['count'] = df.groupby(['username','time'])['username'].transform('count')

这两行代码将为您提供一个更新的数据框df,其中将添加一个名为count.

df = df.drop_duplicates(subset=['username', 'time'], keep='first')

上面的行将删除重复的行。然后你可以绘制df['time']df['count']

plt.scatter(df['time'], df['count'])

推荐阅读