An elegant way to update select cells based with column name
Use pd.where to mask correct values and then replace what you do not need using columns converted to series
df.where(df != '✓', df.columns.to_series(), axis=1)
Outcome
Name A B D
0 Stud1 A C D
1 Stud2 A B D
2 Stud3 B B A
3 Stud4 C B C
Convert columns names to pd.Series
to use as a mapper and use replace
to replace each tick mark '✓'
with its corresponding column name:
df = df.replace('✓', pd.Series(df.columns, df.columns))
Example: For DataFrame df
:
Name A B D
0 Stud1 ✓ C ✓
1 Stud2 ✓ ✓ ✓
2 Stud3 B ✓ A
3 Stud4 C ✓ C
the above code produces:
Name A B D
0 Stud1 A C D
1 Stud2 A B D
2 Stud3 B B A
3 Stud4 C B C