cardamom
cardamom

Reputation: 7421

output where pandas Series of booleans is True

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

Upvotes: 1

Views: 65

Answers (1)

jezrael
jezrael

Reputation: 862661

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')

Upvotes: 2

Related Questions