Sonal
Sonal

Reputation: 47

Adding value to Maximum Value in a dataframe column

I have a dataframe:

Region    |     A      |       B     |      C     |    Total
===============================================================
Africa    |   100.10   |    20.135   |    10.02   |    130.255
---------------------------------------------------------------
Europe    |   200.35   |    50.102   |    16.35   |    266.802
---------------------------------------------------------------
India     |   30.98    |    150.18   |    12.63   |    193.79
---------------------------------------------------------------
Unknown   |   2.36     |    5.108    |    1.96    |    9.428

I want to find the maximum value in a dataframe column and want to add "Unknown" row value to it and remove the "Unknown row".

I did df['A'].max(), df['B'].max() & df['C'].max() which return maximum value in the column but how do I add "Unknown" row value to it?

I expect the output to be:

Region    |     A      |       B     |      C     |    Total
===============================================================
Africa    |   100.10   |    20.135   |    10.02   |    130.255
---------------------------------------------------------------
Europe    |   202.71   |    50.102   |    18.31   |    271.122
---------------------------------------------------------------
India     |   30.98    |    155.288  |    12.63   |    198.898

Explanation:

( df['A'].max() = 200.35 ) + 2.36 = 202.71

( df['B'].max() = 150.18 ) + 5.108 = 155.288

( df['C'].max() = 16.35 ) + 1.96 = 18.31

Upvotes: 1

Views: 49

Answers (1)

BENY
BENY

Reputation: 323226

Using mul with bool mask

df=df.set_index('Region')
df+=(df==df.max()).mul(df.loc['Unknown'])  
df=df.drop('Unknown',axis=0)
df.Total=df.iloc[:,:-1].sum(1)
df
             A        B      C    Total
Region                                 
Africa   100.1   20.135  10.02  130.255
Europe  202.71   50.102  18.31  271.122
India    30.98  155.288  12.63  198.898

Upvotes: 2

Related Questions