LoginSignup
6
1

More than 3 years have passed since last update.

Numpyで特定のindex以外を抽出する方法

Last updated at Posted at 2020-06-04

あるarrayから特定のインデックス以外を抽出する方法です。

# 0~99の数字からランダムに10個取ってくる
arr = np.random.randint(0, 100, 10)
# > array([74, 29,  6, 79, 76, 13,  3, 56, 25, 50])

# 奇数番目の数値をarrから除外したい
odd = [1,3,5,7,9]

# 方法① リスト内包表記
index = [i for i in np.arange(len(arr)) if i not in odd]
arr_even = arr[index]

# 方法② True/Falseでマスキングする
index = np.ones(len(arr), dtype=bool)
index[odd] = False
arr_even = arr[index]

# 方法③ np.delete
arr_even = np.delete(arr, odd)

方法③が一番スッキリしていますが、どれも時間的にはあまり変わらないのでお好きな方法でどうぞ。
そんなわけありませんでした!

@nkay さんが検証してくれました。(コメント参照)

image.png

方法②と方法③はあまり変わらないですが、方法①はarrayのサイズが大きくなると遅くなってしまいますね。

コードも置いておきます。
https://github.com/si1242/machine_leraning_experiments/blob/master/20200605_comparison_qiita.ipynb

6
1
16

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