Help us understand the problem. What is going on with this article?

`np.where`で配列の値を条件にしたがって置き換える

More than 1 year has passed since last update.

np.whereを使いたいとき

numpy arrayの要素が、

  • 閾値以上のとき、ある値に置き換える
  • 閾値以下のとき、ある値に置き換える(optional)

使用例1

>>>import numpy as np
>>>nElems = 5
>>>arr = np.linspace(1, 5, nElems) # array([1., 2., 3., 4., 5.])
>>>np.where(arr > 3, 1, 0)
array([0., 0., 0., 1., 1.])

Additional Notes

np.where(condition)
で条件を満たすindexを返してくれる。

まとめ

np.where(配列の各要素に対する条件, 真ならこの値, 偽ならこの値(optional))

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away