Izak
Izak

Reputation: 23

Get Row and Column name of a specific cell in DataFrame

I have this data frame that represents a correlation matrix of another data frame I have. I want to loop through the correlation matrix and get the name of every row and column where the cell value is True. For example, I want it to print:

REB DREB . . .

enter image description here

Upvotes: 0

Views: 968

Answers (2)

David Erickson
David Erickson

Reputation: 16683

Let's say you have the following dataframe:

df = pd.DataFrame({'AST': {'id': False, 'REB': False, 'FG3a': False},
 'BLK': {'id': False, 'REB': False, 'FG3a': False},
 'DREB': {'id': False, 'REB': True, 'FG3a': False}})

        AST    BLK   DREB
id    False  False  False
REB   False  False   True
FG3a  False  False  False
  1. You can melt the DataFrame and return the rows that you are interested in:

true = df.melt(ignore_index=False)
true[true['value']]

        variable  value
REB     DREB      True
  1. If you want to print, you can do:

true = df.melt(ignore_index=False)
true = true[true['value']]
[print(x,y) for (x,y) in zip(true.index, true['variable'])]

REB DREB
  1. If you want the output in an array, then you can do:

true = df.melt(ignore_index=False).reset_index()
true[true['value']].drop('value', axis=1).values

array([['FG3a', 'BLK'],
       ['REB', 'DREB']], dtype=object)

Upvotes: 1

Marcus Cazzola
Marcus Cazzola

Reputation: 333

reqd_Index = df[df['id']== True].index.tolist()
print(reqd_Index)

Upvotes: 1

Related Questions