1

I have a Series created like this

s = pd.Series({'a': False, 'b': True, 'c': False, 'd': True, 'e': False})

>> s
a    False
b     True
c    False
d     True
e    False
dtype: bool

Is there a way to neatly extract the names of where it is True, staying within Pandas or NumPy and without going back to ordinary Python?

At the moment I am using this:

sdict = s.to_dict()
for item in list(sdict):
    if sdict[item] == True:
        print (item, end=" ")

>> b d
cardamom
  • 6,873
  • 11
  • 48
  • 102

1 Answers1

2

Use boolean indexing with s.index:

print (s.index[s])
Index(['b', 'd'], dtype='object')

print (s.index[s].tolist())
['b', 'd']

print (', '.join(s.index[s]))
b, d

A bit overcomplicated solution with np.where, for fun:

print (s.index[np.where(s)[0]])
Index(['b', 'd'], dtype='object')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252