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

Time:11-17

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?

CodePudding user response:

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
  • Related