【问题标题】:Applying a function on to columns in dataframe and returning to values of two new columns Python将函数应用于数据框中的列并返回两个新列的值 Python
【发布时间】:2018-05-10 12:01:28
【问题描述】:

我有以下 DF 和 f(a,b) 函数:

       A        B

0      5       3
1      4       2
2      7       1

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

我想在 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

【问题讨论】:

  • 以下两种解决方案之一是否有帮助?如果接受,请随意接受(左侧的绿色勾号),或要求澄清。

标签: python pandas function dataframe apply


【解决方案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)

输出:

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

【讨论】:

    【解决方案2】:

    这是一种方式。我强烈建议您不要将 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
    

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2018-04-02
      • 2016-09-13
      • 1970-01-01
      • 2019-06-15
      相关资源
      最近更新 更多