简体   繁体   中英

How to create complicated function in Python?

I have Python Data Frame like below:

df = pd.DataFrame({"code" : [1,1,2,2,3], "value" : [10, 11, 11, 11, 30]})

Next, I found combinations code x value without duble

cc = df.groupby(['code','value']).size().reset_index().rename(columns={0:'count'})
cc

Next, I need to create function where each combination of code x value from cc will be used, and then saved in Data Frame, for example

在此处输入图像描述

for index 0 is code = 1 and value = 10 and I need to function which will iterate for combination code x value for each index and will summarize these value, for example:
for index 0 -> 1+10 = 11
for index 1 - > 1+11 = 12
for index 2 ->2+11 = 13
for index 3 -> 3 +30 = 33
And return results of function in Data Frame like below:

在此处输入图像描述

It's a very simple function... whatever function you want in apply

import math
df = pd.DataFrame({"code" : [1,1,2,2,3], "value" : [10, 11, 11, 11, 30]})
cc = df.groupby(['code','value']).size().reset_index().rename(columns={0:'count'})
cc = cc.assign(result=cc.apply(lambda r: math.sqrt(r.code**2 + r.value**3), axis=1)).rename(columns={"code":"col1","value":"col2"}).drop(columns="count")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM