【问题标题】:Python : TypeError when taking CSV data from url with IPython.displayPython:使用 IPython.display 从 url 获取 CSV 数据时出现 TypeError
【发布时间】:2020-12-25 00:27:14
【问题描述】:

我正在尝试从 python JupyterNotebook 中的直接 URL 获取数据。但我得到的错误真的让我很沮丧。

这是我正在获取的链接:

https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data

我只是将 Jupyter Notebook 功能用作:

from IPython.display import HTML
HTML('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')

我得到的错误如下:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-0a8be2c0a7c6> in <module>
      1 from IPython.display import HTML
----> 2 HTML('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\display.py in __init__(self, data, url, filename, metadata)
    693         if warn():
    694             warnings.warn("Consider using IPython.display.IFrame instead")
--> 695         super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata)
    696 
    697     def _repr_html_(self):

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\display.py in __init__(self, data, url, filename, metadata)
    619 
    620         self.reload()
--> 621         self._check_data()
    622 
    623     def __repr__(self):

C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\display.py in _check_data(self)
    668     def _check_data(self):
    669         if self.data is not None and not isinstance(self.data, str):
--> 670             raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
    671 
    672 class Pretty(TextDisplayObject):

TypeError: HTML expects text, not b'5.1,3.5,1.4,0.2,Iris-setosa\n4.9,3.0,1.4,0.2,Iris-setosa\n4.7,3.2,1.3,0.2,Iris-setosa\n4.6, ....

非常感谢任何帮助。

【问题讨论】:

  • 数据是json格式的吗?
  • 我认为它是 csv 格式 @SandrinJoy
  • 是的,数据是 csv 格式
  • 请在下次提问时提及这些

标签: python html jupyter-notebook ipython data-science


【解决方案1】:

错误是由于HTML() dosent 期望 CSV。

使用 pandas read_csv 轻松方便地读取 CSV 文件:

import pandas as pd
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')
print(data)

输出:

     5.1  3.5  1.4  0.2     Iris-setosa
0    4.9  3.0  1.4  0.2     Iris-setosa
1    4.7  3.2  1.3  0.2     Iris-setosa
2    4.6  3.1  1.5  0.2     Iris-setosa
3    5.0  3.6  1.4  0.2     Iris-setosa
4    5.4  3.9  1.7  0.4     Iris-setosa
..   ...  ...  ...  ...             ...
144  6.7  3.0  5.2  2.3  Iris-virginica
145  6.3  2.5  5.0  1.9  Iris-virginica
146  6.5  3.0  5.2  2.0  Iris-virginica
147  6.2  3.4  5.4  2.3  Iris-virginica
148  5.9  3.0  5.1  1.8  Iris-virginica

【讨论】:

    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多