【问题标题】:boxplot of weekends vs weekdays data in pythonpython中周末与工作日数据的箱线图
【发布时间】:2021-07-15 00:06:38
【问题描述】:

我有每日能源消耗数据。我想绘制周末能源消耗与工作日能源消耗的箱线图。

数据类似这样:

date Energy
2018-01-08 13.690
2018-01-09 5.400
2018-01-10 28.859
2018-01-11 16.132
2018-01-12 15.233
2018-01-15 0.000
2018-01-16 0.000
2018-01-17 20.234
2018-01-18 42.416
2018-01-19 12.956
2018-01-22 17.412
2018-01-23 11.378
2018-01-24 20.749
2018-01-25 18.997
2018-01-26 31.387
2018-01-29 15.025
2018-01-30 20.141
2018-01-31 18.758
2018-02-01 16.275
2018-02-02 6.358

箱线图应该是这样的:

感谢任何帮助。

提前致谢

更新-这是我尝试过的:

我尝试创建一个包含工作日的列和另一个包含周末的列,以便我可以将它们绘制在箱线图中。

data.set_index('real date', inplace= True)
data.index.name = 'date'
data.index = pd.to_datetime(data.index)

data["weekday"]=data.apply(lambda row: row["date"].weekday(),axis=1)
data["weekend"] = (data["weekday"] < 5).astype(int)

keyError 来自第三行。

KeyError Traceback(最近一次调用最后一次) ~\anaconda3\envs\tensorflow\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 3079 尝试: -> 3080 返回 self._engine.get_loc(casted_key) 3081 除了 KeyError 错误:

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: '日期'

【问题讨论】:

  • data.apply(lambda row: row["date"].weekday(),axis=1)row.index.weekday()是不是需要修改,因为日期列被指定为这一行之前的索引?
  • 如果错误消失了,下面的代码应该可以画图了。 data['year'] = data['date'].dt.year;import seaborn as sns;sns.boxplot(data=data,x='year', y='value', hue='weekend')
  • 到目前为止你尝试过什么?你可以看看 matplotlib 或 plotly。

标签: python boxplot


【解决方案1】:

这就是我能够解决我自己的问题的方法:

请注意,我删除了日期作为索引。 “日期”现在是一个专栏,这就是我写的原因:data["date"]

dic={0:'Weekend',1:'Weekday'}
data['month'] = data["date"].dt.strftime('%b,%Y')
data['day'] = data.weekday.map(dic)
a=plt.figure(figsize=(18,4)) 
plt1=sns.boxplot('month','Energy',hue='day',width=0.6,fliersize=3,
                    data=data_d)                                                                                                       

这个博客很有帮助:https://towardsdatascience.com/time-series-analysis-visualization-forecasting-with-lstm-77a905180eba

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2019-01-22
    • 1970-01-01
    • 2019-07-01
    • 2018-02-18
    • 2019-11-02
    相关资源
    最近更新 更多