Pandas if value is equal to 1, then give column name

Viewed 2756

I have a dataframe

   Blue  Red
0   0     0
1   1     0
2   0     1
3   0     0
4   0     0

I want to say if value equals 1, then give the column name. So the expected output is

   Blue  Red
0   0     0
1   Blue  0
2   0     Red
3   0     0
4   0     0

I almost done this in a very complicated way, I was hoping there was a simple way?

2 Answers

Use DataFrame.mask with convert columns to Series for avoid AttributeError: 'Index' object has no attribute '_info_axis_number' (in some newer pandas versions):

df = df.mask(df.eq(1), df.columns.to_series(), axis=1)
print (df)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0

Alternative with numpy.where:

df = pd.DataFrame(np.where(df.eq(1), df.columns, df), 
                  index=df.index, 
                  columns=df.columns)
print (df)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0

This is by iteration over columns and rows: Consider the dataframe is df1:

for name in df1.columns:
    for row in df1.index:
        if df1.loc[row,name] == 1:
            df1.loc[row,name] = name

print(df1)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0
Related