【问题标题】:import a CSV file using its URL using Pandas in Python在 Python 中使用 Pandas 使用其 URL 导入 CSV 文件
【发布时间】:2020-12-08 07:27:08
【问题描述】:

我是 Python 新手,我想将 csv 数据从 .csv url 获取到我的 python 脚本中的数据框,我该怎么做?请帮忙。

我在我的系统(我使用终端打开)上使用 Jupyter Notebook 来编写代码。

以下是我的代码和错误信息。

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv')

错误消息很长,但它是这样开始的:

SSLCertVerificationError                  Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1316                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1317                           encode_chunked=req.has_header('Transfer-encoding'))
   1318             except OSError as err: # timeout error

【问题讨论】:

  • 下载csv文件,添加到同一个文件夹并尝试读取。
  • 什么是完整的回溯,你从哪里运行脚本?如果您收到 GitHub 的 SSL 错误,您可能需要更新计算机上的根证书

标签: python python-3.x pandas csv jupyter-notebook


【解决方案1】:

我对你的代码没有问题:

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv')
df
country year    pop continent   lifeExp gdpPercap
0   Afghanistan 1952    8425333.0   Asia    28.801  779.445314
1   Afghanistan 1957    9240934.0   Asia    30.332  820.853030
2   Afghanistan 1962    10267083.0  Asia    31.997  853.100710
3   Afghanistan 1967    11537966.0  Asia    34.020  836.197138
4   Afghanistan 1972    13079460.0  Asia    36.088  739.981106
... ... ... ... ... ... ...
1699    Zimbabwe    1987    9216418.0   Africa  62.351  706.157306
1700    Zimbabwe    1992    10704340.0  Africa  60.377  693.420786
1701    Zimbabwe    1997    11404948.0  Africa  46.809  792.449960
1702    Zimbabwe    2002    11926563.0  Africa  39.989  672.038623
1703    Zimbabwe    2007    12311143.0  Africa  43.487  469.709298
1704 rows × 6 columns

【讨论】:

  • 这对我不起作用,我收到上面提到的错误。
【解决方案2】:

您必须首先使用 urllib2 库下载 CVS 文件,然后将结果传递给 CSV 库以将该文件读入 Python。这是建议的代码:

import csv
import urllib2

url = 'https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 2019-04-28
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多