Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

はじめに

データ解析コンペに出たりすると,予測結果を専用のフォームから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)
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away