Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Get Index of True Values of a Sequence in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Using Boolean Indexing

import numpy as np
import pandas as pd

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

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

s[s].index.values
array([0, 2, 3, 7])

Using np.nonzero

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

Using np.flatnonzero

np.flatnonzero(s)
array([0, 2, 3, 7])

Using np.where

np.where(s)[0]
array([0, 2, 3, 7])

Using np.argwhere

np.argwhere(s).ravel()
array([0, 2, 3, 7])

Using pd.Series.index

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

Using python’s built-in filter

[*filter(s.get, s.index)]
[0, 2, 3, 7]

Using list comprehension

[i for i in s.index if s[i]]
[0, 2, 3, 7]