简体   繁体   English

将函数应用于数据框中的列并返回两个新列的值Python

[英]Applying a function on to columns in dataframe and returning to values of two new columns Python

I have the following DF and f(a,b) function: 我有以下DF和f(a,b)函数:

       A        B

0      5       3
1      4       2
2      7       1

f(a,b):
 return (a+b,a-b)

I want to a apply f(a,b) on columns A,B ... and return two values into two new columns df[sum,sub] 我想在A,B列上应用f(a,b)...,并将两个值返回到两个新列df [sum,sub]

       A      B       C       D

0      5      3       8       2
1      4      2       6       2
2      7      1       8       6

Using apply with axis=1 使用applyaxis=1

import pandas as pd
df = pd.DataFrame({"A": [5, 4, 7], "B":[3, 2, 1]})

def f(a,b):
    return (a+b,a-b)

df[["sum", "sub"]] = df.apply(lambda row: f(row["A"], row["B"]), axis=1).apply(pd.Series)
print(df)

Output: 输出:

   A  B  sum  sub
0  5  3    8    2
1  4  2    6    2
2  7  1    8    6

This is one way. 这是一种方式。 I strongly recommend you don't use pd.DataFrame.apply with a row-wise calculation, as this unnecessarily sidesteps pandas vectorisation. 我强烈建议您不要将pd.DataFrame.apply与按行计算一起使用,因为这不必要地回避了pandas矢量化。

def f(a, b):
    return a + b, a - b

def foo(df, a, b):
    return f(df[a], df[b])

df['C'], df['D'] = df.pipe(foo, 'A', 'B')

print(df)

   A  B  C  D
0  5  3  8  2
1  4  2  6  2
2  7  1  8  6

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

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