質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

1回答

486閲覧

np.whereでの配列の引数

Lily_1007

総合スコア35

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/06/25 13:55

前提・実現したいこと

知人から頂いたコードで分からない事がありましたので、こちらにてお伺いさせて頂きます。

発生している問題・エラーメッセージ

python

1dists = [0.1, 35. , 54.4, ...] (1*n次元のndarrayです) 2idx = np.where(dists == np.min(dists))[0][0]

分からないこと

[0][0]というものが何を意味するのかが分かりません。
また,無くても正しくidxは出るのではないかと思っておりますので,何故使用する理由がよく分かりませんでした。

np.whereでネットで調べても出てこなかったのでこちらにて質問させていたきました。
よろしくお願いいたします。

補足情報(FW/ツールのバージョンなど)

python3

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

こういう場合の調べ方です。

python

1>>> print(np.where.__doc__) 2 3 where(condition, [x, y]) 4 5 Return elements chosen from `x` or `y` depending on `condition`. 6 7 .. note:: 8 When only `condition` is provided, this function is a shorthand for 9 ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be 10 preferred, as it behaves correctly for subclasses. The rest of this 11 documentation covers only the case where all three arguments are 12 provided. 13 14 Parameters 15 ---------- 16 condition : array_like, bool 17 Where True, yield `x`, otherwise yield `y`. 18 x, y : array_like 19 Values from which to choose. `x`, `y` and `condition` need to be 20 broadcastable to some shape. 21 22 Returns 23 ------- 24 out : ndarray 25 An array with elements from `x` where `condition` is True, and elements 26 from `y` elsewhere. 27 28 See Also 29 -------- 30 choose 31 nonzero : The function that is called when x and y are omitted 32 33 Notes 34 ----- 35 If all the arrays are 1-D, `where` is equivalent to:: 36 37 [xv if c else yv 38 for c, xv, yv in zip(condition, x, y)] 39 40 Examples 41 -------- 42 >>> a = np.arange(10) 43 >>> a 44 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 45 >>> np.where(a < 5, a, 10*a) 46 array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90]) 47 48 This can be used on multidimensional arrays too: 49 50 >>> np.where([[True, False], [True, True]], 51 ... [[1, 2], [3, 4]], 52 ... [[9, 8], [7, 6]]) 53 array([[1, 8], 54 [3, 4]]) 55 56 The shapes of x, y, and the condition are broadcast together: 57 58 >>> x, y = np.ogrid[:3, :4] 59 >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast 60 array([[10, 0, 0, 0], 61 [10, 11, 1, 1], 62 [10, 11, 12, 2]]) 63 64 >>> a = np.array([[0, 1, 2], 65 ... [0, 2, 4], 66 ... [0, 3, 6]]) 67 >>> np.where(a < 4, a, -1) # -1 is broadcast 68 array([[ 0, 1, 2], 69 [ 0, 2, -1], 70 [ 0, 3, -1]])
When only `condition` is provided, this function is a shorthand for ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.

なので、以下を実行します。

python

1>>> print(np.asarray(dists == np.min(dists)).nonzero.__doc__) 2a.nonzero() 3 4 Return the indices of the elements that are non-zero. 5 6 Refer to `numpy.nonzero` for full documentation. 7 8 See Also 9 -------- 10 numpy.nonzero : equivalent function

なので、以下を実行します。

python

1>>> print(np.nonzero.__doc__) 2 3 Return the indices of the elements that are non-zero. 4 5 Returns a tuple of arrays, one for each dimension of `a`, 6 containing the indices of the non-zero elements in that 7 dimension. The values in `a` are always tested and returned in 8 row-major, C-style order. 9 10 To group the indices by element, rather than dimension, use `argwhere`, 11 which returns a row for each non-zero element. 12 13 .. note:: 14 15 When called on a zero-d array or scalar, ``nonzero(a)`` is treated 16 as ``nonzero(atleast1d(a))``. 17 18 .. deprecated:: 1.17.0 19 20 Use `atleast1d` explicitly if this behavior is deliberate. 21 22 Parameters 23 ---------- 24 a : array_like 25 Input array. 26 27 Returns 28 ------- 29 tuple_of_arrays : tuple 30 Indices of elements that are non-zero. 31 32 See Also 33 -------- 34 flatnonzero : 35 Return indices that are non-zero in the flattened version of the input 36 array. 37 ndarray.nonzero : 38 Equivalent ndarray method. 39 count_nonzero : 40 Counts the number of non-zero elements in the input array. 41 42 Notes 43 ----- 44 While the nonzero values can be obtained with ``a[nonzero(a)]``, it is 45 recommended to use ``x[x.astype(bool)]`` or ``x[x != 0]`` instead, which 46 will correctly handle 0-d arrays. 47 48 Examples 49 -------- 50 >>> x = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]]) 51 >>> x 52 array([[3, 0, 0], 53 [0, 4, 0], 54 [5, 6, 0]]) 55 >>> np.nonzero(x) 56 (array([0, 1, 2, 2]), array([0, 1, 0, 1])) 57 58 >>> x[np.nonzero(x)] 59 array([3, 4, 5, 6]) 60 >>> np.transpose(np.nonzero(x)) 61 array([[0, 0], 62 [1, 1], 63 [2, 0], 64 [2, 1]]) 65 66 A common use for ``nonzero`` is to find the indices of an array, where 67 a condition is True. Given an array `a`, the condition `a` > 3 is a 68 boolean array and since False is interpreted as 0, np.nonzero(a > 3) 69 yields the indices of the `a` where the condition is true. 70 71 >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 72 >>> a > 3 73 array([[False, False, False], 74 [ True, True, True], 75 [ True, True, True]]) 76 >>> np.nonzero(a > 3) 77 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2])) 78 79 Using this result to index `a` is equivalent to using the mask directly: 80 81 >>> a[np.nonzero(a > 3)] 82 array([4, 5, 6, 7, 8, 9]) 83 >>> a[a > 3] # prefer this spelling 84 array([4, 5, 6, 7, 8, 9]) 85 86 ``nonzero`` can also be called as a method of the array. 87 88 >>> (a > 3).nonzero() 89 (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))

で、

Returns a tuple of arrays, one for each dimension of `a`, containing the indices of the non-zero elements in that dimension. The values in `a` are always tested and returned in row-major, C-style order.

なので、[0][0]が必要です。

投稿2021/06/25 15:33

ppaul

総合スコア24666

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Lily_1007

2021/06/26 03:04

つまり、まとめると np.whereの説明書をみると, np.whereはnp.nonzeroを使用して書かれていて、np.nonzeroは2次元配列に作用させると答えが2次元配列で返ってくるということでしょうか。今、np.where(dists == np.min(dists))自体、そもそも1*1の配列という認識でよろしいでしょうか? 別にnp.where(dists == np.min(dists))[0]でもarrayで返ってくるので問題は無いように思えます。。
ppaul

2021/06/28 02:57 編集

2次元配列というと正確ではなく、nadarrayのTupleです。nadarrayの次元数は、対象のndarrayと同じです。 np.where(dists == np.min(dists))自体、そもそも1*1の配列という認識でよろしいでしょうか? 違います。 一般的にいって、戻り値は複数の多次元ndexを含みます。 今回は、一次元ですが、長さがいくつになるかは入力次第です。 [0][0]とする理由のひとつは、条件を満たす複数のindexのうち、一番小さいものをとることです。 もう一つの理由は、目視ではなくその値をプログラムで使うなら求める型ではないからでしょう。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問