LoginSignup
1
0

More than 3 years have passed since last update.

Numpy配列のAdvanced Indexingは知らないとわけわからなくなる。([], compare, condition, 条件式, fancy indexing )

Last updated at Posted at 2019-07-22

目的

Keras関連のpythonのコードで、
numpy配列の以下のような処理があり、

test_xxx_prediction[test_xxx_prediction >= 0.5] = 1

※test_xxx_predictionは、numpy配列

numpyの”fancy indexing”というようなものも、知らなかったので、
調査に手間取った。
泥縄式に調べると
numpy配列は、かなり、いろいろなことができることがわかったので、情報共有。

 np.array[条件式]
 np.array[condition]
 
ぐらいで検索したが、うまくかからなかった。

Advanced Indexing

以下など、よくわかるのでは?

Advanced Indexing の例

numpy配列では、以下のような処理ができる。
慣れていないと、随所に、わけがわからないところがあるかも。


>>> a = np.array([0.01, 0.62, 3.55, 0.21, 0.91, 0.0, 3.2, 0.33, 0.45, 0.99])
>>> a
array([0.01, 0.62, 3.55, 0.21, 0.91, 0.  , 3.2 , 0.33, 0.45, 0.99])
>>> a[a < 0.5] = 1.0
>>> a
array([1.  , 0.62, 3.55, 1.  , 0.91, 1.  , 3.2 , 1.  , 1.  , 0.99])
>>>



>>> b = np.array([1, 2, 4, 6, 9])
>>> a[b]
array([0.62, 3.55, 0.91, 3.2 , 0.99])
>>>
>>>

numpy配列でなく、リストでは、当然できません。


>>> aaa = [0.01, 0.62, 3.55, 0.21, 0.91, 0.0, 3.2, 0.33, 0.45, 0.99]
>>> aaa
[0.01, 0.62, 3.55, 0.21, 0.91, 0.0, 3.2, 0.33, 0.45, 0.99]
>>> aaa[aaa < 0.5] = 1.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'list' and 'float'
>>> bbb = [1, 2, 4, 6, 9]
>>> aaa[bbb]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not list
>>>



まとめ

調べるのに時間がかかったので、記事に。

関連(本人)

pythonをストレスなく使う!(結局docs.python.orgのreferenceが納得感が高い気が、、、)
pythonをストレスなく使う!(generatorに詳しくなる。since1975らしい。)
pythonをストレスなく使う!(Pythonでは、すべてがオブジェクトとして実装されている)
pythonをストレスなく使う!(Pylintに寄り添う)
pythonをストレスなく使う!(ExpressionとStatement)
英語と日本語、両方使ってPythonを丁寧に学ぶ。

今後

コメントなどあれば、お願いします。:candy:
勉強します、、、、

1
0
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
1
0