【问题标题】:Unable to plot histograms in jupyter notebook无法在 jupyter notebook 中绘制直方图
【发布时间】:2018-12-10 18:25:41
【问题描述】:

我无法在 Jupyter 笔记本中绘制直方图。这是下面的代码和响应它的错误消息。

import pandas as pd
import numpy as np
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt

housing_data = load_boston()
%matplotlib inline
housing_data.hist(bins = 50, figsize = (20, 15))
plt.show()

KeyError                                  Traceback (most recent call last)
/anaconda3/lib/python3.6/site-packages/sklearn/utils/__init__.py in          __getattr__(self, key)
60         try:
---> 61             return self[key]
62         except KeyError:

KeyError: 'hist'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-17-570a88b85d5d> in <module>()
----> 1 housing_data.hist(bins = 50, figsize = (20, 15))
2 plt.show();

/anaconda3/lib/python3.6/site-packages/sklearn/utils/__init__.py in    __getattr__(self, key)
 61             return self[key]
 62         except KeyError:

---> 63 引发 AttributeError(key) 64 65 def setstate(自我,状态):

AttributeError: hist

我是新手,请帮助我。

【问题讨论】:

  • 您在通话中缺少plot:housing_data.plot.hist(...) 应该这样做
  • @busybear,我尝试使用 Housing_data.plot.hist() 并得到 AttributeError: plot
  • 我的错。我只是假设housing_data 是一个熊猫数据框。 plot.hist 方法特定于 pandas 数据帧。 housing_data 或多或少是一本字典;你需要弄清楚你想如何处理它或者你想从那里绘制什么数据。

标签: python-3.x matplotlib jupyter-notebook


【解决方案1】:
import pandas as pd
import numpy as np
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt

housing_data = load_boston()
%matplotlib inline


pd.DataFrame(housing_data['data']).hist(bins = 50, figsize = (20, 15))

您必须访问包含数据的 numpy 数组字典,然后将其转换为 pandas 数据帧才能使用.hist

【讨论】:

  • 非常感谢。它真的帮助了我
  • 太棒了!很高兴我帮了忙!如果您有任何问题,请随时提问。如果问题得到解答,请检查答案下方的勾号 =)
【解决方案2】:

您没有指定,所以我假设您想绘制“目标”?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston

housing_data = load_boston()
housing_data_2  = ({'target' : list(housing_data['target'])})
df = pd.DataFrame(data=housing_data_2)
df.plot.hist(bins = 50)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    相关资源
    最近更新 更多