我正在使用python 3和jupyter笔记本。我有一个像这样的结构的pandas数据框:
location price
Apr 25 ASHEVILLE 15.0
Apr 25 ASHEVILLE 45.0
Apr 25 ASHEVILLE 50.0
Apr 25 ASHEVILLE 120.0
Apr 25 ASHEVILLE 300.0
<class 'pandas.core.frame.DataFrame'>
我只是想为每个位置创建一个箱线图,以显示每个位置的项目之间的价格范围。
当我运行以下代码时:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
plt.boxplot(postings)
plt.show()
它返回TypeError:unhashable type:'slice'
答案 0 :(得分:4)
我猜你需要同一图表中每个位置的箱线图。 我修改了给定的数据帧,为另一个看起来像 -
的位置添加了样本数据 date location month price
0 25 ASHEVILLE Apr 15.0
1 25 ASHEVILLE Apr 45.0
2 25 ASHEVILLE Apr 50.0
3 25 ASHEVILLE Apr 120.0
4 25 ASHEVILLE Apr 300.0
5 25 NASHVILLE Apr 34.0
6 25 NASHVILLE Apr 55.0
7 25 NASHVILLE Apr 70.0
8 25 NASHVILLE Apr 105.0
9 25 NASHVILLE Apr 85.0
现在,只需在此框架上调用boxplot并提供参数 - column
和by
postings.boxplot(column='price', by='location')
答案 1 :(得分:1)
我猜&#34;价格&#34;是您想要使用boxplotted的数据列。因此,您需要先选择此列,并仅将该列提供给plt.boxplot
。
u = u"""index,location,price
Apr 25,ASHEVILLE,15.0
Apr 25,ASHEVILLE,45.0
Apr 25,ASHEVILLE,50.0
Apr 25,ASHEVILLE,120.0
Apr 25,ASHEVILLE,300.0"""
import io
import pandas as pd
import matplotlib.pyplot as plt
data = io.StringIO(u)
df = pd.read_csv(data, sep=",", index_col=0)
plt.boxplot(df["price"])
plt.show()
答案 2 :(得分:0)