【发布时间】: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。