科学の箱

科学・IT・登山の話題

Python

numpyで配列を抜き出す方法

投稿日:

numpyで配列を抜き出す

まず基本となるやり方

arr = np.arange(50).reshape(5,10)
arr[1:1,]
arr[1:2,]

 

np.arange(50)でまず要素数50であり、一次元の配列を作成する。reshape(5,10)で5次元、要素数10個に整理する。

array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]])

arr[1:1,]の結果は0配列である。これは開始は1であるが、終了1未満になるために抜け出せない。

array([], shape=(0, 10), dtype=int32)

arr[1:2,]で一配列だけ抜き出すことができる。

array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

次に条件付き配列

arr = np.arange(1,11)
barr = arr > 5
arr[barr]

np.arange(1,11)で作成される配列

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

次に5で条件付けをする。arr>5にすると以下のようなboolean配列が取得できる。

array([False, False, False, False, False,  True,  True,  True,  True,  True], dtype=bool)

このboolean配列を元の配列に入れてあげるとarr[barr]

array([ 6,  7,  8,  9, 10])

この操作は一行で済ませることが可能である。

arr[arr>5]

 

 

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

pipインストールでエラーが出る場合

pipインストールでエラーが出る場合 Collecting tensorflow WARNING: Retrying (Retry(total=4, connect=None, read=None, …

no image

python coding styleのツール

Pythonで使えるコーディングツール pep8 flake8 pylint   Related posts:SIGNATE お弁当の需要予測-4特定のパッケージのためのgitignoreを …

no image

automated the boring

まずは肩慣らし print(‘Hello world!’) print(‘What is your name?’) # ask for their na …

no image

selectorとxpathを手軽に取得する方法

スクレイピングをするプログラムを開発するときに対象となる項目を取得するためにselector/xpathで指定する。 Google Chromeではselector/xpath値を簡単に取得できる。 …

no image

RoboBrowserでUser Agentが原因ではねられているとき

RoboBrowserを利用していると通常のブラウザでリクエストした時とは異なりエラーがページが返ってくることが多い。 原因はいくつかあるがまず試したいのはUser-Agentの設定。 RoboBro …

2018年3月
« 2月   4月 »
 1234
567891011
12131415161718
19202122232425
262728293031  

side bar top



アーカイブ

カテゴリー