Home > Mobile >  How to divide each value in column by the maximum value of a subset of that column
How to divide each value in column by the maximum value of a subset of that column

Time:03-30

I am trying to divide each row in a column by the maximum of a sub-list in the column where the sub-list if the column filtered by a category variable

Is there a single line vector equation that creates col3? I have been trying to use groupby with transform(lambda x: x...) but can't seem to get the effect of maxif where it only takes the max of col2 where col1 = the rows with the same category as the row in col2 being divided.

Sample input code:

import pandas as pd

data = {'col1':['A', 'A', 'B', 'B'],
        'col2':[1, 2, 3, 4]}

df = pd.DataFrame(data)

df

Desired output:

col1 col2 col3 explanation
A 1 0.5 e.g. 1/2
A 2 1 e.g. 2/2
B 3 0.75 e.g. 3/4
B 4 1 e.g. 4/4

CodePudding user response:

Sure:

>>> df['col2'] / df.groupby('col1')['col2'].transform(max)
0    0.50
1    1.00
2    0.75
3    1.00

You could then assign that result to a new column of your choice.

  • Related