来自 url 的 Pandas read_csv [英] Pandas read_csv from url

查看:42
本文介绍了来自 url 的 Pandas read_csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 3.x 从给定的 URL 读取 csv 文件:

I'm trying to read a csv-file from given URL, using Python 3.x:

import pandas as pd
import requests

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
s = requests.get(url).content
c = pd.read_csv(s)

我有以下错误

"预期的文件路径名或类文件对象,得到 类型"

"Expected file path name or file-like object, got <class 'bytes'> type"

我该如何解决这个问题?我使用的是 Python 3.4

How can I fix this? I'm using Python 3.4

推荐答案

更新:从 pandas 0.19.2 开始,您现在可以 直接传递read_csv() url,但如果需要身份验证会失败.

UPDATE: From pandas 0.19.2 you can now just pass read_csv() the url directly, although that will fail if it requires authentication.

对于较旧的熊猫版本,或者如果您需要身份验证,或者出于任何其他 HTTP 容错原因:

For older pandas versions, or if you need authentication, or for any other HTTP-fault-tolerant reason:

使用 pandas.read_csv 和一个类似文件的对象作为第一个参数.

Use pandas.read_csv with a file-like object as the first argument.

  • 如果你想从一个字符串中读取 csv,你可以使用 io.StringIO.

对于 URL https://github.com/cs109/2014_data/blob/master/countries.csv,您将获得 html 响应,而不是 原始 csv;您应该使用 github 页面中 Raw 链接给出的 url 来获取原始 csv 响应,即 https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv

For the URL https://github.com/cs109/2014_data/blob/master/countries.csv, you get html response, not raw csv; you should use the url given by the Raw link in the github page for getting raw csv response , which is https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv

示例:

import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))

注意事项:

在 Python 2.x 中,字符串缓冲区对象是 StringIO.StringIO

in Python 2.x, the string-buffer object was StringIO.StringIO

这篇关于来自 url 的 Pandas read_csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆