简体   繁体   English

如何在Python中创建复杂的function?

[英]How to create complicated function in Python?

I have Python Data Frame like below:我有 Python 数据框,如下所示:

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

Next, I found combinations code x value without duble接下来,我发现没有双重的组合代码 x 值

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接下来,我需要创建 function ,其中将使用来自 cc 的代码 x 值的每个组合,然后保存在 Data Frame 中,例如

在此处输入图像描述

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:对于索引 0 是代码 = 1 和值 = 10,我需要 function 它将迭代每个索引的组合代码 x 值并总结这些值,例如:
for index 0 -> 1+10 = 11对于索引 0 -> 1+10 = 11
for index 1 - > 1+11 = 12对于索引 1 - > 1+11 = 12
for index 2 ->2+11 = 13对于索引 2 -> 2+11 = 13
for index 3 -> 3 +30 = 33对于索引 3 -> 3 +30 = 33
And return results of function in Data Frame like below:并在数据框中返回 function 的结果,如下所示:

在此处输入图像描述

It's a very simple function... whatever function you want in apply这是一个非常简单的 function ......无论你想申请什么 function

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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