IPython データサイエンスクックブック memo (1)

1.1 Introduction

%%writefile

IPython magicコマンド。テキストファイルの作製。

インラインの数式は$...$ を使って記述。
独立した数式は $$...$$ を使って記述。

HTML()SVG()YouTubeVideo()

nbviewerを使ってIPythonで生成したJSONテキストを公開可能。

1.2 Data Analysis with IPython

df = pd.read_csv(url, index_col='Date', parse_dates=False, dayfirst=False)
  • pase_dates
    01/01/2013 → 2013-01-01
  • dayfirst
    2013-02-01 → 2013-01-02
df.describe()

サマリー表示

days = np.array(['Monday', 'Tuesday', 'Wednesday', 
                 'Thursday', 'Friday', 'Saturday', 
                 'Sunday'])
df['Weekday'] = days[df.index.weekday]

number → names

df_week.ix[days].plot(lw=3, figsize=(6,4));

-lw
line width - figsize figure size

.ix で行っているのは並べ替えのみ。

1.3 Numpy

%precision 3

ipython のmagicコマンド。数値出力を第3位までに。

n = 10000
x = [random.random() for _ in range(n)]
y = [random.random() for _ in range(n)]
%\time it [x[i] ; y[i] for i in range(n)]
1 loop, best of 3: 250 ms per loop
  • %timeit
    実行時間の計測。複数回実行、最速の実行時間を表示。
%timeit sum(x)  # pure Python
%timeit np.sum(xa)  # NumPy
The slowest run took 25.57 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 6.69 ms per loop
The slowest run took 59.18 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 1.53 ms per loop

numpy使うとこのくらい早くなる。

x[:1000,None]

Noneを使えば次元を増やせる。

1.4 custom magic command

from IPython.core.magic import (register_line_magic, 
                                register_cell_magic)
  • register_line_magic
    行magicコマンドの定義
  • register_cell_magic 列magicコマンドの定義
def load_ipython_extension(ipython):
    ipython.register_magic_function(function, 'cell')

この関数を組み込んでおけば実行時に読まれてmagicコマンドとして登録される。 IPython のInteractiveShellインスタンスを引数に受け取る。

cythonmagicrmagic

cython の関数をセル内で定義、インポート可能。

1.5 Interactive computing

定義したmagicコマンドの引数の指定

  • ipython実行時に指定
ipython --profile=cookbook --RandomMagics.text='Your number is {n}.' --RandomMagics.max=10 --RandomMagics.seed=1
  • 設定ファイルで設定 ~/.ipython/profile_default_ipython_config.py を編集
c.RandomMagics.text = 'random{n}'

Configurableクラス > 設定ファイル  いずれも継承可能

1.6 IPython Kernel

IPythonでカーネルを作ることができる。用途:IPythonのユーザーインターフェースを書き換える。

IPython version5.1.0 ではカーネルの起動の仕方がわからなかった。要調査。