Search code examples
pythonpandaspercentage

How to calculate the percent for values in a column against the column max


My values are = [40,40,40,40,40,33,17]

I want calculate and add them to second column with percentages, so my outcome should be like this:

first_column=[40,40,40,40,40,33,17]

second_column=[100,100,100,100,100,82.5,42.5]

But I want to python to calculate for me and wrote to the second column...

import pandas as pd

import matplotlib.pyplot as plt

# create the dataframe from values in the OP

counts = [40,40,40,40,40,33,17]

df = pd.DataFrame(data=counts, columns=['counts'], index=['A','B','C','D','E','F','G'])

# add a percent column

df['%'] = df.counts.div(df.counts.sum()).mul(100).round(2)

df

This above thinks as the sum of them as 40+40+40... but in my case 100% is 40.


Solution

  • You can use:

    df['%'] = 100 / df['counts'].max() * df['counts']
    print(df)
    
    # Output
       counts      %
    A      40  100.0
    B      40  100.0
    C      40  100.0
    D      40  100.0
    E      40  100.0
    F      33   82.5
    G      17   42.5