I often use python's numpy to format text logs, but at that time I often find out what I've stumbled upon (what if I solve it once)? But I want to fix the point that I think it's okay ...), I will leave it as a memorandum about how to use the return value of np.where, which is hard to come out even if I check it at that time. Please forgive that the content is cheap ...
In the first place, the return value of np.where can get the index information. Let's see that using a two-dimensional numpy array.
test1.py
import numpy as np
array = np.array([["a","b","c"],["d","e","f"],[1,2,3]])
print(np.where(array == "d"))
Execution result
$ python test1.py
(array([1]), array([0]))
The result of this execution visually shows that the string d
is in the ʻarray [1] [0] of the numpy array ʻarray
. Let's see below how to actually handle this return value.
test2.py
import numpy as np
array = np.array([["a","b","c"],["d","e","f"],[1,2,3]])
print(np.where(array == "d"))
print(type(np.where(array == "d")))
print(np.where(array == "d")[0])
print(np.where(array == "d")[1])
print(np.where(array == "d")[0][0])
print(np.where(array == "d")[1][0])
Execution result
$ python test2.py
(array([1]), array([0]))
<class 'tuple'>
[1]
[0]
1
0
Therefore, the return value of np.where
is tuple, and it is necessary to specify the index appropriately according to the desired value.
This time, we want to specify the line (= 1) where the character string d
is, so we usenp.where (array == "d") [0] [0]
.
test3.py
import numpy as np
array = np.array([["a","b","c"],["d","e","f"],[1,2,3]])
print(array[np.where(array == "d")[0][0]][:])
Execution result
$ python test3.py
['d' 'e' 'f']
I will also write that I have tried various things using np.where.
test4.py
import numpy as np
array = np.array([["a","b","c"],["d","e","f"],[1,2,3]])
print(array[np.where(array == "d")])
Execution result
$ python test4.py
['d']
If you enter it directly when specifying the index of the numpy array, the specified element will be returned in the array.
However, this does not give us the value d
.
To get d
itself, you have to specify the index of the returned array as follows.
test5.py
import numpy as np
array = np.array([["a","b","c"],["d","e","f"],[1,2,3]])
print(array[np.where(array == "d")][0])
Execution result
$ python test5.py
d
So far, the purpose of using np.where is to get an index that includes a specific element, so I feel like I can't use it like this, but please forgive me as a bonus ...
Recommended Posts