Charlotte Deng
Charlotte Deng

Reputation: 131

Replace the max value for each column to 0 in Pandas

For example, I have a data set of this:

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

data_df = pd.DataFrame(data)
data_df
   A  B   C
0  1  3   9
1  2  5   0
2  3  1   1

I want to replace the max value for each columns to 0. My desired output is:

   A  B   C
0  1  3   0
1  2  0   0
2  0  1   1

Thank you in advance!

Upvotes: 0

Views: 1509

Answers (2)

Jonas
Jonas

Reputation: 1529

This works if your max value is unique.

Just be aware that idxmax() returns the first index of the maximum value. If the values occurs more often this won't work.

for col in df.columns:
    df.loc[df.idxmax()[col], col] = 0

Upvotes: 1

maziyank
maziyank

Reputation: 616

You can interate through columns, get the max value and replace row with max value:

for col in data_df.columns:
    data_df[col] = data_df[col].apply(lambda x: 0 if x==data_df.max()[col] else x)

Upvotes: 2

Related Questions