Search code examples
pythonpandasnumpydataset

How can I build a search and replace Pandas Python


I have a dataset that looks like this

import pandas as pd
dts1 = pd.DataFrame([[0.5,0.7,0.1,0.9,0.1],
                [0.7,0.9,0.11,0.02,0.1]])
dts1.head()

For each row in the data set I want to replace the max value to 1 and if it's not the maximum then replace it with 0

So each row should look like

0,1,0,0,0

Solution

  • Compare to the max per row and convert the boolean to integer:

    dts1.eq(dts1.max(axis=1), axis=0).astype(int)
    

    Output:

       0  1  2  3  4
    0  0  0  0  1  0
    1  0  1  0  0  0