Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

What I want to do is replace a column value with "0" if, for a given row, that column is not maximal. And conversely, replace the column value with "1" if, for a given row, that column IS maximal.

My data looks like this:

data = {

    "A": [1, 2, 3],

    "B": [3, 5, 1],

    "Max": ["B", "B", "A"]

}

data_df = pd.DataFrame(data)

print(data_df)

   A  B Max

0  1  3   B

1  2  5   B

2  3  1   A

But I want it to look like

   A  B Max

0  0  1   B

1  0  1   B

2  1  0   A

1 Answer

0 votes
by (25.1k points)

You can do it by simply iterating over each column check if dataframe's max column is equal to col.

for col in ['A','B']:

    data_df[col] = data_df['Max'].eq(col).astype(int)

Browse Categories

...