ManOnTheMoon
ManOnTheMoon

Reputation: 597

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

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

Upvotes: 6

Views: 1137

Answers (2)

jezrael
jezrael

Reputation: 863031

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

Upvotes: 3

user7864386
user7864386

Reputation:

Try:

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

Output:

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

Upvotes: 3

Related Questions