How can I use the column_name of a dataframe as a value on the rows?

Viewed 93

I have this Framework, 2 columns (Blue and Red) and values (0,1)

**Blue   Red**
   0      1
   1      1

I wanna a Dataframe result as this, If the column Red has value=1, replace this 1 with the name_column Red

**Blue   Red**
   0    Red
 Blue   Red

I can do it this with "for" but, do you know another way to do this? Thanks

4 Answers

One way is to multiply df and an array of same shape:

df * np.broadcast_to(df.columns.values, df.shape)

   Blue  Red
0        Red
1  Blue  Red

Which makes you end up with strings in all cells.


Another solution is to use where for each column

df.apply(lambda s: s.where(s.eq(0), s.name))

Which makes you end up with mixed types.


As a general rule of thumb, it's good to have single-typed arrays for each column.

using apply function is more efficient. I am using astype(object) so I can use the replace function:

import pandas as pd
df = pd.DataFrame([[0, 1], [1, 0]], columns=['**Blue', 'Red**'])

df = df.apply(lambda x: x.astype(object).replace(1, x.name.replace("**", '')))
print(df)

using np.where

df1 = pd.DataFrame(np.where(df.eq(1), df.columns, df), columns=df.columns)

print(df1)

   Blue  Red
0     0  Red
1  Blue  Red

You can call this function , maybe it might helps you:

def func(val):
    if (val==1):
        return "red"
    else:
        return 'Blue'
val=int(input())
print(func(val))
Related