LoginSignup
50
44

More than 5 years have passed since last update.

numpy tips

Posted at

配列周りの関数

機能 コマンド 備考
リスト→配列 numpy.array(リスト変数) 変換元の変数はタプルでもOK
リスト→配列(型指定) numpy.array(リスト変数, numpy.データ型)
配列→リスト ndarray.tolist()
配列サイズ ndarray.shape
配列次元数 ndarray.ndim
配列の要素数 ndarray.size
配列のバイト数 ndarray.nbytes
配列の内容 numpy.type(ndarray)
配列の変数型 ndarray.dtype
変数型の変更 ndarray.astype(numpy.データ型)

配列の結合

dstack、hstack、vstackの3種類。それぞれの頭文字がdepth wise (along third axis)、horizontally (column wise)、vertically (row wise)を表している

以下の変数で試す

>>> a = np.array((1,2,3))
>>> b = np.array([4,5,6])
>>> a
array([1, 2, 3])
>>> b
array([4, 5, 6])

dstack

depth wise (along third axis)
転置してから結合ってことかな?

>>> np.dstack((a,b))
array([[[1, 4],
        [2, 5],
        [3, 6]]])

hstack

horizontally (column wise)

>>> np.hstack((a,b))
array([1, 2, 3, 4, 5, 6])

vstack

vertically (row wise)

>>> np.vstack((a,b))
array([[1, 2, 3],
       [4, 5, 6]])

配列のソート

ndarray.sort()を利用すればいい。この場合、ndarray変数の中身がソートされる。
numpy.sort(ndarray)とした場合は、ソートした結果のコピーが返却される。
ちなみに、sortした場合のインデックスを返すndarray.argsort()なんてのもある。
ndarray.sort()はsortする軸の指定があるので、実行時に注意が必要。

以下の変数をソートしてみる

>>> hoge = np.array([[1,3,2],[6,5,4],[9,7,8]])
>>> hoge
array([[1, 3, 2],
       [6, 5, 4],
       [9, 7, 8]])

通常のソート。
行ごとにソートが走る。

>>> np.sort(hoge)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

axisを使えば、列ごとにソートする。

>>> np.sort(hoge, axis=0)
array([[1, 3, 2],
       [6, 5, 4],
       [9, 7, 8]])

Structured Arraysにして配列に名前つければ、特定の列指定でソートできるみたい。
しかし、Structured Arraysを上手く作る方法がわからん・・・

*numpyデータ型一覧
調べたら書く

50
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
44