LoginSignup
150
144

More than 3 years have passed since last update.

Numpy100本ノックで出会った「こりゃあ、便利だなぁ~」と思った関数一覧

Last updated at Posted at 2020-04-09

概要

会社の研修中にNumpy100本ノックに取り組みさせられましたが、そもそも関数を知らないと倒せない問題が数多くあり、知識不足を痛感しました。
その、僕が初めましての関数の中でも「便利だなぁ~」と思ったものを備忘録を兼ねてご紹介するのがこの記事になります。

筆者プロフィール

プログラミング歴:約1年(Pythonのみ)
Numpyはこの本で勉強しました。

初めに

初めての関数に出会ったら、ググるよりも先にhelpを見た方が圧倒的に理解が早いです。
helpは

np.info([関数名])
ex) np.info(np.add)

jupyter notebookであれば

[関数名]?
ex) np.add?

で表示されます。
関数の説明のみならず、引数の種類や使用例まで載っており、情報量がとても多いです。
英語なので慣れていないと苦痛に感じるかも知れませんが、是非参考にしていただきたいです。

「便利だなぁ~」な関数

np.flip

配列を反転します。

a = np.arange(10)
np.flip(a)
-> array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

ベクトルであればスライス([::-1])で事足りますが、行列の場合などに重宝しそうです。
行列の場合、axisを指定すると任意の方向にひっくり返すことができます。

a = np.arange(9).reshape(3,3)
np.flip(a)
-> array([[8, 7, 6],
          [5, 4, 3],
          [2, 1, 0]])

np.flip(a, axis=0)
->array([[6, 7, 8],
         [3, 4, 5],
         [0, 1, 2]])

np.flip(a, axis=1)
-> array([[2, 1, 0],
          [5, 4, 3],
          [8, 7, 6]])

np.eye

単位行列を生成します。

np.eye(3)
-> array([[1., 0., 0., 0.],
          [0., 1., 0., 0.],
          [0., 0., 1., 0.],
          [0., 0., 0., 1.]])

np.diag

対角成分を抽出します。

a = np.random.randint(0,10, (3,3))
print(a)
-> [[5 2 8]
    [2 7 5]
    [5 1 0]]
p.diag(a)
-> array([5, 7, 0])

np.tile

配列を敷き詰めます。

a = np.array([[0, 1], [1, 0]])
np.tile(a, (2,2))
-> array([[0, 1, 0, 1],
          [1, 0, 1, 0],
          [0, 1, 0, 1],
          [1, 0, 1, 0]])

np.bincount

配列中の数値(非負、int型)をカウントし、その値のindexに格納します。

a = np.random.randint(0, 10, 10)
print(a)
-> array([8 6 0 8 4 6 2 5 2 1])
np.bincount(a)
-> array([1, 1, 2, 0, 1, 1, 2, 0, 2], dtype=int64)

np.repeat

要素を指定した数だけ繰り返します。

np.repeat(3, 4)
-> array([3, 3, 3, 3])

np.roll

配列を指定した数だけ右にシフトします。

a = np.arange(10)
np.roll(a, 2)
-> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])

np.flatten

元の配列を1次元配列に直します。

a = np.arange(9).reshape(3,3)
print(a)
-> [[0 1 2]
    [3 4 5]
    [6 7 8]]
b = a.flatten()
print(b)
-> [0 1 2 3 4 5 6 7 8]

np.nonzero

0以外の値が含まれているindexを教えてくれます。

a = np.array([1,0,0,1])
b = np.array([1,1,1,1])
print(np.nonzero(a))
-> (array([0, 3], dtype=int64),)
print(np.nonzero(b))
-> (array([0, 1, 2, 3], dtype=int64),)

np.copysign

第1引数の符号を第2引数と同じ符号に変換します。

a = np.arange(10)
b = np.repeat([1, -1], 5)
np.copysign(a, b)
-> array([ 0.,  1.,  2.,  3.,  4., -5., -6., -7., -8., -9.])

np.intersect1d

2配列の共通する要素を取り出します。

a = np.arange(10)
b = np.arange(5, 15)
np.intersect1d(a, b)
-> array([5, 6, 7, 8, 9])

最後に

こういった関数は暗記するものではありませんが、そもそも知らないと使うことができません。
ご紹介した関数達が皆様の頭の片隅にでも残っていただけるととても嬉しいです!

150
144
5

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
150
144