done is better than perfect

自分が学んだことや、作成したプログラムの記事を書きます。すべての記載は他に定める場合を除き個人的なものです。

numpy.arrayやscipy.sparse.lil_matrixなどで指定した行だけでできた行列を作る

自分用メモ書き.ある行列から指定した行だけ(例えば[1,3,4]みたいな感じでリストで抜き出したい行が入っているとする)でできた行列を作る.

In [1]: choices = [[0, 1, 2, 3], [10, 11, 12, 13],
   ...:   [20, 21, 22, 23], [30, 31, 32, 33]]

In [3]: import numpy as np

In [4]: choices = np.array(choices)

In [5]: choices
Out[5]:
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33]])

In [13]: choices[[1,2]]
Out[13]:
array([[10, 11, 12, 13],
       [20, 21, 22, 23]])

In [14]: choices[[0,2]]
Out[14]:
array([[ 0,  1,  2,  3],
       [20, 21, 22, 23]])

In [15]: from scipy.sparse import lil_matrix

In [16]: l = lil_matrix(choices)

In [17]: l
Out[17]:
<4x4 sparse matrix of type '<class 'numpy.int64'>'
    with 15 stored elements in LInked List format>

In [18]: l[[0,2]]
Out[18]:
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 7 stored elements in LInked List format>

In [19]: l[[0,2]].todense()
Out[19]:
matrix([[ 0,  1,  2,  3],
        [20, 21, 22, 23]], dtype=int64)

行が飛んでいるのはご愛嬌.

教訓

ドキュメント読みましょう