Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of series where value is True

Tags:

python

pandas

How do I select only True values?

myindex=['a', 'b', 'c' , 'd']
myseries=pd.Series([True, True, False, True], index=myindex)

a     True
b     True
c    False
d     True
dtype: bool

What I have tried:

myseries.where(myseries == True)

This includes "c" while I need to return a list of a, b and d

like image 422
shantanuo Avatar asked Jan 31 '19 04:01

shantanuo


2 Answers

If you just want to return the index which is a, b, c, d in your case use the index attribute:

myindex=['a', 'b', 'c' , 'd']
myseries=pd.Series([True, True, False, True], index=myindex)

a     True
b     True
c    False
d     True
dtype: bool

myseries[myseries].index
>> Index(['a', 'b', 'd'], dtype='object')

If you want it as a list:

myseries[myseries].index.tolist()
>> ['a', 'b', 'd']
like image 169
Mohit Motwani Avatar answered Oct 02 '22 00:10

Mohit Motwani


The code myseries[myseries] returns

a    True
b    True
d    True
dtype: bool

If you specifically want a list of ['a', 'b', 'd'] then you can it by list(myseries[myseries].index).

like image 40
kevins_1 Avatar answered Oct 02 '22 02:10

kevins_1