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

Time:07-19

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:

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

CodePudding user response:

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
  • Related