'Fetch a df column title/header for data in a specific row satisfying a condition

I have one hot encoded a text data so that I looks like this:

enter image description here

I am trying to write code that will give me the column name for where 1 is found for respective row.

e. g.

labels = df.iloc[index, ......]

where index will go for from 0 to 32937 (for each column) and in .... I want to specify the column header for which the data == 1 is to be found. I hope it's clear what I want to do.



Solution 1:[1]

IIUC:

def fn(row):

    if row['negative'] == 1:
            return 'negative'

    elif row['neutral'] == 1:
        return 'neutral'
    
    elif row['positive'] == 1:
        return 'positive'

Create a function as above and use apply method:

train_dataset['new_col'] = train_dataset.apply(fn, axis=1)

Solution 2:[2]

I tried this:

labels = train_dataset.iloc[index,train_dataset.iat[index,1]-1]

and:

labels = train_dataset.columns[train_dataset.iat[index,1]]

the second one is closer to my answer, but I am not sure how to tweek it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohammad Mufassir Khan
Solution 2 Subbu VidyaSekar