Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas: Groupby.transform -> assign specific values to column

In general terms, is there a way to assign specific values to a column via groupby.transform(), where the groupby size is known in advance?

For example:

df = pd.DataFrame(data = {'A':[10,10,20,20],'B':['abc','def','ghi','jkl'],'GroupID':[1,1,2,2]})

funcDict = {'A':'sum','B':['specific_val_1', 'specific_val_2']}

df = df.groupby('GroupID').transform(funcDict)

where the result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index A B
1 20 specific_val_1
2 20 specific_val_2
3 40 specific_val_1
4 40 specific_val_2

>Solution :

transform can not accepted dict , so we can do agg with merge

out = df.groupby('GroupID',as_index=False)[['A']].sum()
out = out.merge(pd.DataFrame({'B':['specific_val_1', 'specific_val_2']}),how='cross')
Out[90]: 
   GroupID   A               B
0        1  20  specific_val_1
1        1  20  specific_val_2
2        2  40  specific_val_1
3        2  40  specific_val_2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading