您正在创建一个流并将其直接传递给 pandas。我认为你需要将一个类似文件的对象传递给 pandas。看一眼这个答案 https://stackoverflow.com/a/32400969/900271寻找可能的解决方案(使用 post 而不是进入请求)。
另外,我认为您使用的带有重定向的登录网址无法正常工作。我知道我在这里建议了 http://ramhiser.com/2012/11/23/how-to-download-kaggle-data-with-python-and-requests-dot-py/。但我最终没有使用 is 因为发布请求调用没有处理重定向(我怀疑)。
我最终在项目中使用的代码是这样的:
def from_kaggle(data_sets, competition):
"""Fetches data from Kaggle
Parameters
----------
data_sets : (array)
list of dataset filenames on kaggle. (e.g. train.csv.zip)
competition : (string)
name of kaggle competition as it appears in url
(e.g. 'rossmann-store-sales')
"""
kaggle_dataset_url = "https://www.kaggle.com/c/{}/download/".format(competition)
KAGGLE_INFO = {'UserName': config.kaggle_username,
'Password': config.kaggle_password}
for data_set in data_sets:
data_url = path.join(kaggle_dataset_url, data_set)
data_output = path.join(config.raw_data_dir, data_set)
# Attempts to download the CSV file. Gets rejected because we are not logged in.
r = requests.get(data_url)
# Login to Kaggle and retrieve the data.
r = requests.post(r.url, data=KAGGLE_INFO, stream=True)
# Writes the data to a local file one chunk at a time.
with open(data_output, 'wb') as f:
# Reads 512KB at a time into memory
for chunk in r.iter_content(chunk_size=(512 * 1024)):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
使用示例:
sets = ['train.csv.zip',
'test.csv.zip',
'store.csv.zip',
'sample_submission.csv.zip',]
from_kaggle(sets, 'rossmann-store-sales')
您可能需要解压缩文件。
def _unzip_folder(destination):
"""Unzip without regards to the folder structure.
Parameters
----------
destination : (str)
Local path and filename where file is should be stored.
"""
with zipfile.ZipFile(destination, "r") as z:
z.extractall(config.raw_data_dir)
所以我从来没有真正将其直接加载到 DataFrame 中,而是先将其存储到磁盘中。但是您可以修改它以使用临时目录,并在读取文件后删除它们。