4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

numpyのwhere

Last updated at Posted at 2016-09-22

webで調べても、なかなかバチッと内容が検索できなかったのでメモ(マジで短いっす、、)

知りたいこと

>> import numpy as np
>> np.where(A>5, 1, -1)

なるコードがあって、?と思った

動かしてみる

まずは準備

>> import numpy as np
### まずは配列を作りますね
>> A = np.arange(10,0,-1)
### 内容確認
>> A
array([10,  9,  8,  7,  6,  5,  4,  3,  2,  1])

確認!

### 内側から確認してきましょう
>> A>5
[ True  True  True  True  True False False False False False]
### -> 条件を満たせばTrue、満たさなければFalseを返すんですね
### whereをかましてみる
>> np.where(A>5)
(array([0, 1, 2, 3, 4]),)
### -> 条件を満たす要素が取り出せましたね。
### さて、お題の内容
>> np.where(A>5, 1, -1)
array([ 1,  1,  1,  1,  1, -1, -1, -1, -1, -1])
### -> 条件を満たせたら2つ目の引数の値"1"を、満たせなかったら3つ目の引数の値"-1"を返すっぽい
### ↑の内容を念のため他の値で確認
>> np.where(A>5,2,0)
array([2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
### -> 合ってたっぽいですね。
```

SQLの`where`句のような感じですかね?(違うかな?!)

# Reference
- 公式ドキュメント
http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
 今回の記事をベースにすると少しは理解が進みますかね?!
4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?