Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - Group by and apply custom function in pandas data frame

I have a df as below:

enter image description here

I would like to group by id and flag and create a new column in the df which is the result of: [sum(value1)/sum(value2)] * 12. Therefore I will need the result to be:

enter image description here

I have created a function:

 `def calculation (value1, value2):

       result = (value1/value2) * 12

       return(result)`

Could you advise which is the best way to apply this function along with the grouping, in order to get the desired output? Many thanks

question from:https://stackoverflow.com/questions/65904321/group-by-and-apply-custom-function-in-pandas-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following code should work.

import pandas as pd
df = pd.DataFrame({"id" : [1,1,2,2],"flag":["A","B","B","A"],"value1":[520,200,400,410],"value2":[12,5,11,2]})
def calculation(value1, value2):
    result = (value1/value2) * 12
    return(result)
df.groupby(['id','flag']).apply(lambda x: calculation(x['value1'],x['value2'])).astype(int)

You just have to use the following for groupby and apply.

df.groupby(['id','flag']).apply(lambda x: calculation(x['value1'],x['value2'])).astype(int)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...