user2978216
user2978216

Reputation: 568

get indexes with condition

How do I find a position(index) of all entries of search_value?

import pandas as pd
import numpy as np
search_value=8
lst=[5, 8, 2, 7, 8, 8, 2, 4]
df=pd.DataFrame(lst)
df["is_search_value"]=np.where(df[0]==search_value, True, False)
print(df.head(20))

Output:

   0  is_search_value
0  5            False
1  8             True
2  2            False
3  7            False
4  8             True
5  8             True
6  2            False
7  4            False

Desirable output:

1 4 5

If search_value is 10 than desirable output:

None

Upvotes: 5

Views: 16999

Answers (3)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210812

If you pass to np.where() only condition - it'll return indices of matched elements:

In [29]: np.where(df[0]==search_value)
Out[29]: (array([1, 4, 5], dtype=int64),)

For custom Pandas indices:

In [39]: df = pd.DataFrame(lst, index=np.arange(8)[::-1])

In [40]: df
Out[40]:
   0
7  5
6  8
5  2
4  7
3  8
2  8
1  2
0  4

In [41]: df.index[np.where(df[0]==search_value)]
Out[41]: Int64Index([6, 3, 2], dtype='int64')

Upvotes: 1

C. Yduqoli
C. Yduqoli

Reputation: 1761

with pandas

>>> (pd.Series([5, 8, 2, 7, 8, 8, 2, 4]) == 8).nonzero()
(array([1, 4, 5], dtype=int64),)

Upvotes: -1

Alexander
Alexander

Reputation: 109510

You can use enumerate in a conditional list comprehension to get the index locations.

my_list = [5, 8, 2, 7, 8, 8, 2, 4]
search_value = 8
>>> [i for i, n in enumerate(my_list) if n == search_value]
[1, 4, 5]

If the search value is not in the list, then an empty list will be returned (not exactly None, but still a falsey).

Using pandas, you can use boolean indexing to get the matches, then extract the index to a list:

df[df[0] == search_value].index.tolist()

Using an empty list will satisfy the condition for None (they both evaluate to False). If you really need None, then use the suggestion of @cᴏʟᴅsᴘᴇᴇᴅ.

Upvotes: 4

Related Questions