I am doing a groupby practice. But it returning dict not dataframe. I fallowed some of the solutions from stack-overflow even no luck.
My code :
result[comNewColName] = sourceDF.groupby(context, as_index=False)[aggColumn].agg(aggOperation).reset_index()
and I tried:
result[comNewColName] = sourceDF.groupby(context)[aggColumn].agg(aggOperation).reset_index()
and
result[comNewColName] = sourceDF.groupby(context, as_index=False)[aggColumn].agg(aggOperation)
all three cases, I am getting dict only. But I should get dataframe
here:
comNewColName = "totalAmount"
context =['clientCode']
aggColumn = 'amount'
aggOperation = 'sum'
Need help please:
CodePudding user response:
If need new column created by aggregeted values use GroupBy.transform
, but assign to sourceDF
:
sourceDF[comNewColName] = sourceDF.groupby(context)[aggColumn].transform(aggOperation)
Your solution return DataFrame
:
df = sourceDF.groupby(context)[aggColumn].agg(aggOperation).reset_index()
print (type(df))