LoginSignup
0
0

More than 5 years have passed since last update.

データ解析コンペ等でCSVファイルを提出するとき,Pandasから直接サブミットする

Last updated at Posted at 2018-11-28

はじめに

データ解析コンペに出たりすると,予測結果を専用のフォームからCSVで提出することって多いですよね.
そんなとき,予測結果を一旦CSVで保存して,マウスでポチポチやるのは面倒くさいかと思います.
ここでは,スクリプト中でPandasから直接CSVファイルをPOSTする方法を紹介します.

手順

1. 提出APIを解析する

まず,どのような形式でPOSTするかを解析します.
ブラウザの開発者ツールを使って,トラフィックやソースを見て推測します

2. requestsを使って投げる

requests.postは,ファイルのストリームを渡すとmultipartで投げてくれます.
http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
ここを,BytesIOのストリームに置き換えることでスクリプトから提出します.

import io
import requests

def submit(df, filename, url, headers={}):
    # CSV形式の文字列を取得
    csv = df.to_csv(header=True, index=False)
    # byte型に変換して,BytesIOでstreamにする
    stream = io.BytesIO(csv.encode())
    # requestsでPOSTする
    response = requests.post(url, files={'file': (filename, stream)}, headers=headers)
    return response

# 例えばJWTトークンで認証を行っている場合
url = 'https://data-competition.example.com/submit'
token = 'xxxx.xxxxxxxxx.xxxxxxxxxxx'
res = submit(df, filename='submission.csv',
             url=url, headers={'authorization': token})
print(res)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0