Colaboratory
よく使うショートカットキー
Esc
セル編集から Focus を外す
C-m
or ⌘-m
が prefix
a
/ b
: 前/後にセルを追加
n
/ p
次/前のセルに移動
d
: セル削除
-
: カーソル位置でセル分割
h
: ショートカットキー一覧
m
: テキストのセルに変換
⌘-Enter
: 評価
Alt-Enter
: 評価して下にセルを挿入
⌘-/
: 現在の行をコメント化(toggle)
思考停止コピペコード
copype.py%load_ext google.colab.data_table
import google
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import altair as alt
from IPython.display import display
from pprint import pprint
plt_jp.py!pip install japanize-matplotlib > /dev/null
import japanize_matplotlib
copype_bq.pyfrom google.cloud import bigquery
google.colab.auth.authenticate_user()
project_id = ""
client = bigquery.Client(project=project_id)
query = '''
'''
df = client.query(query).to_dataframe()
copype_bq_table.py# テーブル名から
table = bigquery.TableReference.from_string(bq_table)
bqclient.list_rows(table).to_dataframe(create_bqstorage_client=True)
copype_sheet.pyimport google
google.colab.auth.authenticate_user()
creds, _ = google.auth.default()
import gspread
sheet_url = ''
gs = gspread.authorize(creds)
worksheet = gs.open_by_url(sheet_url).get_worksheet(0)
# worksheet = gs.open_by_url(...).worksheet('Sheet1')
df = pd.DataFrame(worksheet.get_all_values())
'''
# 前にデータ以外がある & 末尾に合計がある時の整形
cell = worksheet.find("ヘッダ左上セル")
start_row = cell.row
columns = worksheet.row_values(start_row)
columns
df = pd.DataFrame(worksheet.get_all_values()[start_row:-1], columns=[])
'''
https://docs.google.com/spreadsheets/d/{spreadsheet_id}/export?format=csv
にアクセスすることでcsvエクスポートできるので、公開のシートであれば認証なしでこれが動くので楽、シートは gid クエリパラメータ
read_csv.pypd.read_csv('https://docs.google.com/spreadsheets/d/{ID}/export?format=csv')
transport.pyimport google
creds, _ = google.auth.default()
# requests
from google.auth.transport.requests import AuthorizedSession
authed_session = AuthorizedSession(credentials)
response = authed_session.get('...')
# colab の urlib3 は古くてサンプルコードはそのまま動かない
!pip install -q -U google-auth urllib3
import urllib3
from google.auth.transport.urllib3 import AuthorizedHttp
authed_http = AuthorizedHttp(creds)
copype_tf.pyimport tensorflow as tf
import tensorflow_probability as tfp
Kernel 再起動
restart.pyimport IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)
どうせ無料なので思考停止で GPU 使う
これコードからできないのかな?
! でコマンド
!cat /proc/cpuinfo
, !free -h
など
!pip install {pkg}
できる
カレントディレクトリの移動
% cd PATH
BigQuery dry-run
BigQuery クライアントの第2引数目が Config
dry_run.pyjob_config = bigquery.QueryJobConfig()
job_config.dry_run = True
job = client.query(query, job_config)
# 以下のように処理バイト数見れる
fields = ['total_bytes_processed', 'total_bytes_billed']
for field in fields:
print(field, getattr(job, field))
BigQuery maximum_bytes_billed
クエリ発行時にスキャンサイズで制限をかけられる、Console のように scan サイズ見えないときの安全装置
maximum_bytes_billed.pyjob_config = bigquery.QueryJobConfig()
job_config.maximum_bytes_billed = 5_000_000_000 # 5GB
result = client.query(query, job_config) # <- Error when it scans over than 5GB
制限を超えた場合は 400 が返ってくる、画面サイズによっては右にちょっとスクロールしないとエラーメッセージが見えないのでクエリの Syntax Error と一瞬では区別がつきにくい
> Query exceeded limit for bytes billed: 5000000000. 5578424320 or higher required.
! command の出力見たいことないので /dev/null へリダイレクトする
!pip install tfcausalimpact > /dev/null
Magic Command
load_ext & unload_ext
IPython の拡張をロードする
よく使うもの
%load_ext google.colab.data_table
テーブル見やすくする、dataframe など
data_tablefrom google.colab import data_table
data_table.DataTable(data.airports(), include_index=False, num_rows_per_page=10)
グラフで日本語を使う
! pip install japanize-matplotlib
ファイルアップロード
upload.pyfrom google.colab import files
uploaded = files.upload()
read_file.pyuploaded[filename] # bytes
list(uploaded.values())[0] # ファイル名を入力するのダルいので1ファイルならこう読むかな
import pandas as pd
import io
bytes = list(uploaded.values())[0]
data = pd.read_csv(io.StringIO(bytes.decode('utf-8')))
data.head()
Google Drive に CSV で書き出す
Spreadsheet API を叩くより、まるごと書き出したいだけなら csv として Drive へ書き出して spreadsheet で開くのが楽
たぶんドライブルートには書けない、 /My Drive/
は必要
巨大な DataFrame を書いても Spreadsheet でまともに開けない、5000行ぐらいならすっといけるかな?
write_to_drive.pyfrom google.colab import drive
drive.mount('/drive')
df.to_csv('/drive/My Drive/test.csv')
# pickle
!mkdir -p '/drive/My Drive/colab/20230402_hoge/'
df.to_pickle('/drive/My Drive/colab/20230402_hoge/df.pkl')
ただ書き出す(Drive に永続化しない)のであればおもむろに /content
以下に書いてダウンロードしてもいい
write.pywith open(f'/content/output.tsv', 'w', encoding="utf-8") as f:
f.write(tsv)
Form の出し方
インタラクティブな notebook を作るのに便利
コメントで制御できる
form.pytext = 'value' # @param {type:"string"}
dropdown = '1st option' #@param ["1st option", "2nd option", "3rd option"]
date_input = '2018-03-22' #@param {type:"date"}
boolean_checkbox = True #@param {type:"boolean"}
boolean_dropdown = True #@param ["False", "True"] {type:"raw"}
Vega dataset
よく目にする from vega_datasets import data
しているやつ
グラフライブラリの描画テストなどによくでてくる
IPython.display
なんかいろいろ表示できる
from IPython.display import display, Markdown
display(Markdown(...))
で markdown を表示
横長の DataFrame をちょっと確認する
最後に評価した値が出力されるので、単に df
と評価することがあるが、カラムが多すぎると省略されてしまう
df.head().transpose()
などして転置させて眺めるとよい
1カラムが長い時
長い文字列が入ってる時など見づらい
pd.set_option("display.max_colwidth", 1000)
して display
itables.pyimport itables
itables.show(df)
# 折り返しするには css でやる...
css = """
<style>
td {
white-space: normal !important;
word-wrap: break-word !important;
}
</style>
"""
# CSSを適用
from IPython.core.display import HTML
display(HTML(css))
Docs など Google API を叩く
Oauth 認証画面つくらないといけない API でも Colab にのっかればちょっと楽
AuthorizedSession
を使うと認証情報付けた request
インスタンスが得られる
from google.auth.transport.urllib3 import AuthorizedHttp
もあるけど Colab のデフォルトではバージョンで動かない? 2.17.3 だった
googleapi.pyimport google
from google.auth.transport.requests import AuthorizedSession
google.colab.auth.authenticate_user()
creds, project = google.auth.default()
client = AuthorizedSession(creds)
resp = client.get(f'https://www.googleapis.com/drive/v2/files/{doc_id}/comments')
monospace で表示
たまにアスキーアート的なアノテーション付きの text の diff などを表示したいことがある
vscode やブラウザ上での表示を含めて等幅にしたい
あれこれがんばるより HTML として描画したほうが簡単
monospaced.pyfrom IPython.display import HTML, display
def print_monospaced(text: str):
html_output = f'<pre style="font-family: monospace;">{text}</pre>'
display(HTML(html_output))
過去のセルの評価結果を得る
_{index}
でその評価番号のセルの出力を得られる
_i{index}
でその評判号のセルの入力を得られる