python - 如果包含 x 标签,则熊猫图显示错误
问题描述
下面是我的数据框:
Quantity Ordered Price Each Sales Sales in $Mn Month
01 10903 1.811768e+06 1.822257e+06 1.82
02 13449 2.188885e+06 2.202022e+06 2.20
03 17005 2.791208e+06 2.807100e+06 2.81
04 20558 3.367671e+06 3.390670e+06 3.39
05 18667 3.135125e+06 3.152607e+06 3.15
06 15253 2.562026e+06 2.577802e+06 2.58
07 16072 2.632540e+06 2.647776e+06 2.65
08 13448 2.230345e+06 2.244468e+06 2.24
09 13109 2.084992e+06 2.097560e+06 2.10
10 22703 3.715555e+06 3.736727e+06 3.74
11 19798 3.180601e+06 3.199603e+06 3.20
12 28114 4.588415e+06 4.613443e+06 4.61
如果我运行:
df1.plot(kind='line', x='Month', y='Sales in $Mn')
我收到此错误:
KeyError Traceback (most recent call last) ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in
get_loc(self, key, method, tolerance) 2888 try:
-> 2889 return self._engine.get_loc(casted_key) 2890 except KeyError as err:
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: 'Month'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last) <ipython-input-287-b425a6b1ccd1> in <module>
----> 1 df1.plot(kind='line', x='Month', y='Sales in $Mn', color='orange')
~\anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, *args, **kwargs)
912 if is_integer(x) and not data.columns.holds_integer():
913 x = data_cols[x]
--> 914 elif not isinstance(data[x], ABCSeries):
915 raise ValueError("x must be a label or position")
916 data = data.set_index(x)
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900 if self.columns.nlevels > 1:
2901 return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903 if is_integer(indexer):
2904 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2889 return self._engine.get_loc(casted_key)
2890 except KeyError as err:
-> 2891 raise KeyError(key) from err
2892
2893 if tolerance is not None:
KeyError: 'Month'
但是,如果我不包含x
参数,我会得到正确的绘图,“月份”会自动在 x 轴上显示:
df1.plot(kind='line', y='Sales in $Mn')
可能是什么原因?
解决方案
原因Month
不是列,而是index
,因此无法按列名选择它。
如果省略参数x
,则 forx
是使用的索引值,因此您只能使用第二种解决方案。
如果检查DataFrame.plot.line
:
参数
x
标签或位置,可选
允许绘制一列与另一列。如果未指定,则使用 DataFrame 的索引。
推荐阅读
- reactjs - 如何使用 React Hooks 添加 cookie 或本地存储
- c++ - 第二次调用 cin.ignore 删除第一个字符的函数
- ruby-on-rails - Cocoon:更新时如何隐藏某个列
- scala - Scala XML 提取逗号分隔符中的元素
- ios - 为什么我的按钮在 Swift Playgrounds 中不起作用?
- swift - 调整 UIImage 大小在 Swift 中保持图像质量
- google-bigquery - 处理卡在步骤 WriteSuccessfulRecords ... 使用模板 Pub/Sub -> BigQuery 时
- javascript - 保持 requestanimationframe 在选项卡开关上运行
- javascript - 使用 Cheerio 获取元素内部的元素
- c - 在 C 中显示文件内容 - 写访问错误