RogerKint
RogerKint

Reputation: 652

Use column names as values in pandas depending on whether value is true or false

I have a df thats look like this

   500  600  700  800
0   Tr  Fls  Fls  Fls
1   Tr  Tr   Tr   Fls
2 ...

And I want to turn it into this

   Value
0  500
1  500
1  600
1  700
2 ....

How would I go about doing this?

Upvotes: 0

Views: 23

Answers (1)

Panda Kim
Panda Kim

Reputation: 13212

Example

data = {'500': {0: 'Tr', 1: 'Tr'},
        '600': {0: 'Fls', 1: 'Tr'},
        '700': {0: 'Fls', 1: 'Tr'},
        '800': {0: 'Fls', 1: 'Fls'}}
df = pd.DataFrame(data)

output(df):

    500 600 700 800
0   Tr  Fls Fls Fls
1   Tr  Tr  Tr  Fls

Code

When df value is 'Tr':

df[df=='Tr'].stack().reset_index(level=1)['level_1'].to_frame('Value')

result:

    Value
0   500
1   500
1   600
1   700

Upvotes: 2

Related Questions