Ben Chuanlong Du's Blog

It is never too late to learn.

Get Index of True Values of a Sequence in Python

Using Boolean Indexing

In [1]:
import numpy as np
import pandas as pd

s = pd.Series([True, False, True, True, False, False, False, True])
s[s].index
Out[1]:
Int64Index([0, 2, 3, 7], dtype='int64')

Use .values if you need a np.array object.

In [6]:
s[s].index.values
Out[6]:
array([0, 2, 3, 7])

Using np.nonzero

In [7]:
np.nonzero(s)
Out[7]:
(array([0, 2, 3, 7]),)

Using np.flatnonzero

In [8]:
np.flatnonzero(s)
Out[8]:
array([0, 2, 3, 7])

Using np.where

In [9]:
np.where(s)[0]
Out[9]:
array([0, 2, 3, 7])

Using np.argwhere

In [13]:
np.argwhere(s).ravel()
Out[13]:
array([0, 2, 3, 7])

Using pd.Series.index

In [14]:
s.index[s]
Out[14]:
Int64Index([0, 2, 3, 7], dtype='int64')

Using python's built-in filter

In [15]:
[*filter(s.get, s.index)]
Out[15]:
[0, 2, 3, 7]

Using list comprehension

In [17]:
[i for i in s.index if s[i]]
Out[17]:
[0, 2, 3, 7]
In [ ]:
 

Comments