HP_17
HP_17

Reputation: 203

Pandas groupby apply customized function to each group

I have a table with multiple columns. For one of the columns AC, I need to replace it with Result AC as shown in the table below

enter image description here

The function has a pseudo code as below:

For each unique address:
If 
# of unique(AC) < Value in column B AND 
len(Top 1 (unique(AC))) != len(Top 2 (unique(AC))):
return mode(air_conditioning) 

Else
For each unique(AC), calculate sum(area)
If Top 1 (sum(area)) > Top 2 (SUM(area)):
return air_conditioning which has Top 1 (SUM(building_area))

Else
For each unique(AC), SUM(value)
return air_conditioning with Top 1 (SUM(value))
 

Upvotes: 2

Views: 240

Answers (1)

wwnde
wwnde

Reputation: 26676

Groupby, transfrom sum should do

df['col2']=df.groupby('col1')['col2'].transform('sum')

Upvotes: 5

Related Questions