IPythonの使い方

IPythonを使ってみたメモです。

IPython

IPythonはPythonの拡張で対話式のシェルで操作します。
データの操作性やmatplotlibによるデータ可視化に優れている点など、
データサイエンスの分野で特に人気の様です。

インストール

pipでインストールします。

# pip install ipython
Collecting ipython
  Downloading ipython-4.1.1-py3-none-any.whl (737kB)
    100% |????????????????????????????????| 737kB 661kB/s
      :
      :
# ipython --version
4.1.1

起動・終了

コンソール上でipythonと打てばREPLの様に起動します。
In [xx] という番号付のコンソールが表示され、番号は連番になってます。

# ipython
Python 3.5.1 (default, Jan 25 2016, 06:24:26)
Type "copyright", "credits" or "license" for more information.

IPython 4.1.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:

終了はexitで抜けれます。

In [77]: exit

変数への代入、出力

変数a,bに代入

In [11]: a = 1000
In [12]: b = 'STRING'

a,bを出力

In [13]: a
Out[13]: 1000

In [14]: b
Out[14]: 'STRING'

オブジェクトの整形出力

配列などを自動できれいに整形して出力されます。
printで出力するのと比較すると違いが分かります。

In [16]: from numpy import random

In [17]: rand_data = {i : random.randn() for i in range(5)}

In [18]: rand_data
Out[18]:
{0: 0.4827829161560025,
 1: -0.13593089767787286,
 2: -0.21895313995682036,
 3: -0.11102199172076664,
 4: 0.7332104138256875}

In [20]: print(rand_data)
{0: 0.4827829161560025, 1: -0.13593089767787286, 2: -0.21895313995682036, 3: -0.11102199172076664, 4: 0.7332104138256875}

タブ補完

Linuxのコンソールの様にタブ補完ができます。
2つの変数を定義。

In [21]: test_num = 1234

In [22]: test_user = 'mike'

test_まで入力してタブを押すと候補が表示されます。

In [23]: test_
test_num   test_user

配列を定義。

In [23]: list = [1, 2, 3, 4, 5]

list.まで入力してタブ補完で配列のメソッドが表示されます。

In [24]: list.
list.append   list.clear    list.copy     list.count    list.extend   list.index    list.insert   list.pop      list.remove   list.reverse  list.sort

In [24]: list.c
list.clear  list.copy   list.count

下記の様にライブラリに対してもタブ補完ができます。

In [25]: import numpy

In [26]: numpy.
numpy.ALLOW_THREADS          numpy.byte        numpy.fromiter         numpy.maximum          numpy.round_
numpy.BUFSIZE                numpy.byte_bounds numpy.frompyfunc       numpy.maximum_sctype   numpy.row_stack
numpy.CLIP                   numpy.bytes0      numpy.fromregex        numpy.may_share_memory numpy.s_
numpy.ComplexWarning         numpy.bytes_      numpy.fromstring       numpy.mean             numpy.safe_eval
numpy.DataSource             numpy.c_          numpy.full             numpy.median           numpy.save
numpy.ERR_CALL               numpy.can_cast    numpy.full_like        numpy.memmap           numpy.savetxt
numpy.ERR_DEFAULT            numpy.cast        numpy.fv               numpy.meshgrid         numpy.savez
numpy.ERR_IGNORE             numpy.cbrt        numpy.generic          numpy.mgrid            numpy.savez_compressed
numpy.ERR_LOG                numpy.cdouble     numpy.genfromtxt       numpy.min              numpy.sctype2char
numpy.ERR_PRINT              numpy.ceil        numpy.get_array_wrap   numpy.min_scalar_type  numpy.sctypeDict
numpy.ERR_RAISE              numpy.cfloat      numpy.get_include      numpy.minimum          numpy.sctypeNA
numpy.ERR_WARN               numpy.char        numpy.get_printoptions numpy.mintypecode      numpy.sctypes
numpy.FLOATING_POINT_SUPPORT numpy.character   numpy.getbufsize       numpy.mirr             numpy.searchsorted
numpy.FPE_DIVIDEBYZERO       numpy.chararray   numpy.geterr           numpy.mod              numpy.select
numpy.FPE_INVALID            numpy.choose      numpy.geterrcall       numpy.modf             numpy.set_numeric_ops
numpy.FPE_OVERFLOW           numpy.clip        numpy.geterrobj        numpy.msort            numpy.set_printoptions

イントロスペクション

?を付けるとオブジェクトの情報が出力されます。
docstringが存在する場合は、定義された情報が表示されます。

数値の変数を表示

In [11]: a = 1000
In [26]: a?
Type:        int
String form: 1000
Docstring:
int(x=0) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given.  If x is a number, return x.__int__().  For floating point
numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base.  The literal can be preceded by '+' or '-' and be surrounded
by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4

文字列の変数を出力

In [12]: b = 'STRING'
In [27]: b?
Type:        str
String form: STRING
Length:      6
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

辞書の変数を出力

In [28]: rand_data?
Type:        dict
String form: {0: 0.4827829161560025, 1: -0.13593089767787286, 2: -0.21895313995682036, 3: -0.11102199172076664, 4: 0.7332104138256875}
Length:      5
Docstring:
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)

メソッドのdocstringを表示

In [29]: random.rand?
Docstring:
rand(d0, d1, ..., dn)

Random values in a given shape.

Create an array of the given shape and propagate it with
random samples from a uniform distribution
over ``[0, 1)``.

Parameters
----------
d0, d1, ..., dn : int, optional
    The dimensions of the returned array, should all be positive.
    If no argument is given a single Python float is returned.

Returns
-------
out : ndarray, shape ``(d0, d1, ..., dn)``
    Random values.

See Also
--------
random

Notes
-----
This is a convenience function. If you want an interface that
takes a shape-tuple as the first argument, refer to
np.random.random_sample .

Examples
--------
>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],  #random
       [ 0.37601032,  0.25528411],  #random
       [ 0.49313049,  0.94909878]]) #random
Type:      builtin_function_or_method

マジックコマンド

マジックコマンドはIpythonで使用できる補助ツールコマンドです。
%magicと実行すると全マジックコマンドの詳細が表示されます。

In [37]: %magic

IPython's 'magic' functions
===========================
          :
          :
          :
Currently the magic system has the following functions:
%alias:
    Define an alias for a system command.

    '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'

    Then, typing 'alias_name params' will execute the system command 'cmd
    params' (from your underlying operating system).

    Aliases have lower precedence than magic functions and Python normal
    variables, so if 'foo' is both a Python variable and an alias, the
    alias can not be executed until 'del foo' removes the Python variable.

    You can use the %l specifier in an alias definition to represent the
    whole line when the alias is called.  For example::

      In [2]: alias bracket echo "Input in brackets: <%l>"


%alias_magic:
    ::

      %alias_magic [-l] [-c] name target

    Create an alias for an existing line or cell magic.

    Examples
    --------
    ::

      In [1]: %alias_magic t timeit
      Created `%t` as an alias for `%timeit`.
      Created `%%t` as an alias for `%%timeit`.

      In [2]: %t -n1 pass
      1 loops, best of 3: 954 ns per loop

      In [3]: %%t -n1
         ...: pass
         ...:
      1 loops, best of 3: 954 ns per loop

      In [4]: %alias_magic --cell whereami pwd
      UsageError: Cell magic function `%%pwd` not found.
      In [5]: %alias_magic --line whereami pwd
      Created `%whereami` as an alias for `%pwd`.

      In [6]: %whereami
      Out[6]: u'/home/testuser'

    positional arguments:
      name        Name of the magic to be created.
      target      Name of the existing line or cell magic.

    optional arguments:
      -l, --line  Create a line magic alias.
      -c, --cell  Create a cell magic alias.
          :
          :
          :
          :

マジックコマンドの実行

クイックリファレンス

%quickrefはIpythonのクイックリファレンスを表示します。

In [36]: %quickref

IPython -- An enhanced Interactive Python - Quick Reference Card
================================================================
          :
          :
          :
System commands:

!cp a.txt b/     : System command escape, calls os.system()
cp a.txt b/      : after %rehashx, most system commands work without !
cp ${f}.txt $bar : Variable expansion in magics and system commands
files = !ls /usr : Capture sytem command output
files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
          :
          :
          :
%alias:
    Define an alias for a system command.
%alias_magic:
    ::
%autocall:
    Make functions callable without having to type parentheses.
%autoindent:
    Toggle autoindent on/off (if available).
%automagic:
    Make magic functions callable without having to type the initial %.
%bookmark:
    Manage IPython's bookmark system.
%cat:
    Alias for `!cat`
%cd:
    Change the current working directory.
%clear:
    Alias for `!clear`
%colors:
    Switch color scheme for prompts, info system and exception handlers.
%config:
    configure IPython
%cp:
    Alias for `!cp`
%cpaste:
    Paste & execute a pre-formatted code block from clipboard.
          :
          :
          :
コマンド入力履歴

%histはコマンド履歴を表示します。

In [39]: %hist
!pwd
ip_info = !ifconfig eth0 | grep "inet"
ip_info[0].strip()
!ps -ef
!ps -ef | grep python
ip_info = !ip addr | grep "inet"
ip_info[0].strip()
ip_info[0]
ip_info
ip_info[0].strip()
a = 1000
b = 'STRING'
a
b
rand_data = {i : random.randn() for i in range(5)}
from numpy import random
rand_data = {i : random.randn() for i in range(5)}
rand_data
          :
          :
          :
処理時間計測

%timeで命令の実行時間を計測します。

In [73]: %time list1 = [1, 2, 3, 4, 5] * 1000000
CPU times: user 15.8 ms, sys: 15.7 ms, total: 31.5 ms
Wall time: 31.8 ms

In [74]: %time list2 = [1, 2, 3, 4, 5] * 2000000
CPU times: user 48.7 ms, sys: 79.9 ms, total: 129 ms
Wall time: 129 ms

%timeitは%timeと似てますが、複数回の計測を行って、その平均が出力されます。

In [75]: %timeit list1 = [1, 2, 3, 4, 5] * 1000000
The slowest run took 17.65 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 21.6 ms per loop

In [76]: %timeit list2 = [1, 2, 3, 4, 5] * 2000000
10 loops, best of 3: 58.4 ms per loop
ブックマーク

%bookmarkはディレクトリをブックマークする機能です。

In [69]: %bookmark nodejs /usr/local/nodejs/

In [71]: cd nodejs
(bookmark:nodejs) -> /usr/local/nodejs/
/usr/local/nodejs

入出力変数

コマンドを実行した結果を保持する変数です。
_は1つ前の出力が保持されます。

In [44]: 2 * 24
Out[44]: 48

In [45]: _
Out[45]: 48

__は2つ前の出力が保持されます。

In [47]: 5 * 100
Out[47]: 500

In [48]: 2 * 24
Out[48]: 48

In [49]: __
Out[49]: 500

_iに行番号を指定すると、その行番号の入力が表示されます。
_に行番号を指定すると、その行番号の出力が表示されます。

In [50]: 2 * 24
Out[50]: 48

In [51]: _i50
Out[51]: '2 * 24'

In [52]: _50
Out[52]: 48

OSコマンド実行

!を頭につけるとシステムコマンドを実行します。

In [1]: !pwd
/root

OSコマンドの結果を変数で受け取ることもできます。

In [6]: ip_info = !ip addr | grep "inet"

In [9]: ip_info
Out[9]:
['    inet 127.0.0.1/8 scope host lo',
 '    inet6 ::1/128 scope host ',
 '    inet 192.168.247.128/24 brd 192.168.247.255 scope global eno16777736',
 '    inet6 fe80::20c:29ff:fe38:a162/64 scope link ']

マジックコマンドの%aliasを使うとllなども定義できます。

In [53]: !ll
/bin/bash: ll: コマンドが見つかりません

In [54]: %alias ll ls -l

In [55]: ll
合計 5288
drwxr-xr-x  2 root root       6  125 01:36 Desktop
drwxr-xr-x  2 root root       6  125 01:36 Documents
drwxr-xr-x  2 root root       6  125 01:36 Downloads
drwxr-xr-x  2 root root       6  125 01:36 Music
drwxr-xr-x  2 root root       6  125 01:36 Pictures
drwxr-xr-x  2 root root       6  125 01:36 Public
drwxr-xr-x  2 root root       6  125 01:36 Templates
drwxr-xr-x  2 root root       6  125 01:36 Videos
          :
          :


終わり。



【参考】
IpythonのO'Reillyも出ていますが、今回の参考はこちら
Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理