3

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
Hariom Singh
  • 3,512
  • 6
  • 28
  • 52
user2978216
  • 474
  • 2
  • 6
  • 19
  • 1
    If you don't pass True and False to np.where, it returns indices (`np.where(df[0]==search_value)`). You'll get `(array([1, 4, 5]),)`. – ayhan Jan 18 '18 at 08:10
  • @ayhan if I don't pass True and False I'm getting error "ValueError: Length of values does not match length of index" – user2978216 Jan 18 '18 at 08:12
  • Are you sure? `np.where(df[0]==search_value)` returns `(array([1, 4, 5]),)` in your example. – ayhan Jan 18 '18 at 08:13

3 Answers3

3

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ᴘᴇᴇᴅ.

Alexander
  • 105,104
  • 32
  • 201
  • 196
1

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')
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
0

with pandas

>>> (pd.Series([5, 8, 2, 7, 8, 8, 2, 4]) == 8).nonzero()
(array([1, 4, 5], dtype=int64),)
C. Yduqoli
  • 1,706
  • 14
  • 18