【问题标题】:passing rows of dataframe as argument to a function in python将数据帧的行作为参数传递给python中的函数
【发布时间】:2021-03-12 07:47:19
【问题描述】:

我正在尝试将数据框的列作为参数传递给按行方式运行,但我以错误结束。 我尝试循环执行,因为我的实际数据框和函数只需要循环。

def sum(x, y, z):
     return x + y + z
Input = pd.DataFrame({'A': [1, 2,3], 'B': [10, 20,22],'C':[4,5,6]})
output = pd.DataFrame({'output': [15, 27,31]})

##What I tried, but this tells me it needs more arguments
for a in Input:
    sum(a)

任何人都可以帮助我,因为我需要迭代数据帧的所有行作为函数的参数,因此数据帧的短列数等于函数中的参数数

【问题讨论】:

    标签: python pandas list dataframe data-manipulation


    【解决方案1】:

    试试这个

    Input.apply(lambda row : sum(row.A, row.B, row.C), axis=1)
    

    axis = 1,列级别的平均值。可以参考pandas apply 它要求更多参数,因为它不知道您要对哪一列进行操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 2020-04-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2017-06-04
      • 2023-03-28
      相关资源
      最近更新 更多