HappyPy
HappyPy

Reputation: 10697

get index of boolean values in pandas - python

a=pd.DataFrame({'a1':[1,2,3,4],'a2':[5,6,7,8]})
c=pd.DataFrame({'c1':[True,False,True,True],'c2':[True,False,False,True]})

How can I get the index of the elements in columns a1 and a2 which are True in columns c1 and c2 respectively?

The index of a1 should be [0,2,3] and the index of a2 [0,3]. The result could be a list of indexes like [[0,2,3],[0,3]].

Upvotes: 2

Views: 3582

Answers (2)

jezrael
jezrael

Reputation: 862641

I think you need where:

c.columns = a.columns
df1 = a.where(c)
idx = [df1[x].dropna().index.tolist() for x in df1]
print (idx)
[[0, 2, 3], [0, 3]]

Another solution:

c.columns = a.columns
idx = list(a.where(c).stack().reset_index()
            .groupby('level_1')['level_0'].apply(list))
print (idx)
[[0, 2, 3], [0, 3]]

Upvotes: 4

piRSquared
piRSquared

Reputation: 294258

It isn't clear what you want exactly.

This is an approach using stack

a.stack().index[c.stack().values].to_series()

0  a1    (0, a1)
   a2    (0, a2)
2  a1    (2, a1)
3  a1    (3, a1)
   a2    (3, a2)
dtype: object

If you want just the list of index values

a.index.values[c.values.any(1)]

array([0, 2, 3])

Upvotes: 2

Related Questions