[PYTHON] Get a row containing a specific element in np.where

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 ...

Get a row containing a specific element in np.where

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']

bonus

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

Get a row containing a specific element in np.where
Extract lines containing a specific "string" in Pandas
Get the number of specific elements in a python list
I get a UnicodeDecodeError in mecab-python3
Count specific strings in a file
I get a KeyError in pyclustering.xmeans
Save a specific variable in tensorflow.session
Get a Boolean in Flask's request
How to get a specific column name and index name in pandas DataFrame
How to get a stacktrace in python
Get a Unicode JSON string containing Japanese.
I can't get the element in Selenium!
Get a token for conoha in python
Get a domain owned by a specific organization
If branch depending on whether there is a specific element in the list
[Python] Get the files in a folder with Python
When I get a chromedriver error in Selenium
Read a file containing garbled lines in Python
Get the caller of a function in Python
Get only the subclass elements in a list
Clone with a specific branch / tag in GitPython
Get a panoramic image in Google Street View
Sort dict in dict (dictionary in dictionary) with a specific key
Get a glimpse of machine learning in Python
Enter a specific value for variable in tensorflow
Create a package containing global commands in Python
How to count numbers in a specific range
Get the value of a specific key in a list from the dictionary type in the list with Python
I get a java.util.regex.PatternSyntaxException when splitting a string in PySpark
[Python] Get element by specifying name attribute in BeautifulSoup
Save tweets containing specific keywords in CSV on Twitter
BigQuery-If you get a Reason: responseTooLarge error in Python
Get a participant's username and screen name in Slack
Stop an instance with a specific tag in Boto3
Get the value of a specific key up to the specified index in the dictionary list in Python
A Python program that collects tweets containing specific keywords daily and saves them in csv