python - 为什么 R 的 read.csv() 可以从 GitLab URL 读取 CSV 而 pandas 的 read_csv() 不能?

标签 python r pandas read.csv

我注意到 Pandas 的 read_csv() 无法读取托管在 GitLab 上的公共(public) CSV 文件:

import pandas as pd
df = pd.read_csv("https://gitlab.com/stragu/DSH/-/raw/master/Python/pandas/spi.csv")

我得到的错误(截断):

HTTPError                                 Traceback (most recent call last)
<ipython-input-3-e1c0b52ee83c> in <module>
----> 1 df = pd.read_csv("https://gitlab.com/stragu/DSH/-/raw/master/Python/pandas/spi.csv")

[...]

~\Anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650 
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 403: Forbidden

然而,使用 R,基函数 read.csv() 愉快地读取它:

df <- read.csv("https://gitlab.com/stragu/DSH/-/raw/master/Python/pandas/spi.csv")
head(df)
#>   country_code year   spi
#> 1          AFG 2020 42.29
#> 2          AFG 2019 42.34
#> 3          AFG 2018 40.61
#> 4          AFG 2017 38.94
#> 5          AFG 2016 39.65
#> 6          AFG 2015 38.62

reprex package 创建于 2020-10-29 (v0.3.0)

知道这是为什么吗?R 是如何实现的?

使用的版本:

  • R 4.0.3
  • python 3.7.9
  • Pandas 1.1.3

最佳答案

如果您正在寻找解决方法,我建议您通过 requests 发出 GET 请求图书馆:

import requests
from io import StringIO

url = "https://gitlab.com/stragu/DSH/-/raw/master/Python/pandas/spi.csv"
df = pd.read_csv(StringIO(requests.get(url).text))
df.head()
  country_code  year        spi
0          AFG  2020  42.290001
1          AFG  2019  42.340000
2          AFG  2018  40.610001
3          AFG  2017  38.939999
4          AFG  2016  39.650002

至于“为什么”的部分,我看到了read_csv internally uses urllib for standard URLs ,显然有问题的 API 可能会阻止请求,因为它认为您是爬虫。如果我重复相同的过程,但添加了“User-Agent” header ,请求就会成功。

TLDR; pandas 做了什么和失败了什么:

from urllib.request import Request, urlopen

req = Request(<URL>)
urlopen(req).read() # fails

pandas 应该做些什么才能让它起作用:

req = Request(<URL>)
req.add_header('User-Agent', <literally anything>)
urlopen(req).read() # succeeds

关于python - 为什么 R 的 read.csv() 可以从 GitLab URL 读取 CSV 而 pandas 的 read_csv() 不能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64585328/

相关文章:

r - summary.rms(sfit) : adjustment values not defined here or with datadist for some variables 中的错误

python - 如何使用python将富文本格式复制到剪贴板

r - 如何使用 roxygen 包从 dplyr 导入管道运算符 %>%

python - 利用 "Copy-on-Write"将数据复制到 Multiprocessing.Pool() 工作进程

r - 测量数据框中所有先前值的最大值

python - 在 pandas 或 python 中逐组比较 2 列

python - 在 python/pandas 中一次更改多列的数据类型

python - python类型转换AttributeError : 'str' object has no attribute 'astype'

python - Peewee 在迁移过程中不使用主键递增整数字段

python - 编写 Python 音乐流媒体