Home > database >  other than max value, replace all value to 0 in each column (pandas, python)
other than max value, replace all value to 0 in each column (pandas, python)

Time:12-16

i have a df which I want to replace values that are not the max value for each column to 0.

code:

data = {
    "A": [1, 2, 3],
    "B": [3, 5, 1],
    "C": [9, 0, 1]
}

df = pd.DataFrame(data)

sample df:

   A  B   C
0  1  3   9
1  2  5   0
2  3  1   1

result trying to get:

   A  B   C
0  0  0   9
1  0  5   0
2  3  0   0

kindly advise. many thanks

CodePudding user response:

Try:

df[df!=df.max()] = 0

Output:

   A  B  C
0  0  0  9
1  0  5  0
2  3  0  0

CodePudding user response:

Use DataFrame.where with compare max values :

df = df.where(df.eq(df.max()), 0)
print(df)
   A  B  C
0  0  0  9
1  0  5  0
2  3  0  0
  • Related