2017-04-20 10 views
2

나는 csv fileKaggle에 직접 가져 와서 다른 방법을 시도해 보았습니다. 성공하지 못한 채로 pandas DataFrame에 직접 가져 왔습니다.다운로드 url에서 pandas DataFrame 가져 오기 Kaggle csv

로그인 요청을 보내야합니다. 이것은 내가 지금까지 가지고있는 것입니다 :

import requests 
import pandas as pd 
from io import StringIO 

# Link to the Kaggle data set & name of zip file 
login_url = 'http://www.kaggle.com/account/login?ReturnUrl=/spacex/spacex-missions/downloads/database.csv' 

# Kaggle Username and Password 
kaggle_info = {'UserName': "user", 'Password': "pwd"} 

# Login to Kaggle and retrieve the data. 
r = requests.post(login_url, data=kaggle_info, stream=True) 
df = pd.read_csv(StringIO(r.text)) 

r은 페이지의 html 콘텐츠를 반환합니다. CParserError: Error tokenizing data. C error: Expected 1 fields in line 13, saw 6

내가 솔루션을 검색했지만, 지금까지 아무것도 내가 일을 시도했습니다 df = pd.read_csv(url)는 CParser 오류를 제공합니다.

답변

0

스트림을 만들고 팬더에 직접 전달합니다. 나는 당신이 판다 (pandas)에 물건과 같은 파일을 전달할 필요가 있다고 생각합니다. 가능한 해결책은 this answer입니다 (게시물을 사용하고 요청에 포함되지 않음).

또한 리디렉션을 사용하는 로그인 URL이 그대로 작동하지 않는다고 생각합니다. I know i suggested that here. 하지만 게시물 요청 요청 (내가 용의자) 리디렉션을 처리하지 않았기 때문에 사용하지 않는 결국.

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에로드 한 것이 아니라 디스크에 먼저 저장했습니다. 하지만 임시 디렉터리를 사용하도록 수정하고 파일을 읽은 후에 파일을 삭제하면됩니다.

+0

Actaully 저는 팬더가 지퍼로 찍힌 상태에서 CSV 파일을 읽을 수 있다고 생각합니다. http://stackoverflow.com/questions/18885175/read-a-zipped-file-as-a-pandas-dataframe –