将具有常量参数的函数应用于 pandas 数据框 [英] apply function with constant parameter to pandas dataframe

查看:33
本文介绍了将具有常量参数的函数应用于 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pandas 数据框,我创建了一个函数.我想将此函数应用于数据帧的每一行.然而,该函数有第三个参数,它不是来自数据帧,可以说是常量.

I have a pandas dataframe, and I created a function. I would like to apply this function to each row of the dataframe. However the function has a third parameter that does not come from the dataframe and is constant so to say.

import pandas as pd

df = pd.DataFrame(data = {'a':[1, 2, 3], 'b':[4, 5, 6]})

def add(a, b, c):
    return a + b * c

df['c'] = add(df['a'], df['b'], 2)

我想我必须使用 apply 函数,但我不知道如何传递这个常量参数.

I think I have to use the apply function but I don't see how I would pass this constant argument.

print df
>>    a  b   c
>> 0  1  4  10
>> 1  2  5  14
>> 2  3  6  18

推荐答案

我在 c 列中得到了一些不同的输出.如果需要按行处理,将 axis=1 添加到 申请:

I get a bit different output in c column. If need process by rows add axis=1 to apply:

df['c'] = add(df['a'],df['b'],2)
df['d'] = df.apply(lambda x: add(x['a'], x['b'], 2), axis=1)
print (df)
   a  b   c   d
0  1  4   9   9
1  2  5  12  12
2  3  6  15  15

<小时>

def add(a,b,c):
    #operator precedence, need ()
    return (a + b) * c

df['c'] = add(df['a'],df['b'],2)
df['d'] = df.apply(lambda x: add(x['a'], x['b'], 2), axis=1)
print (df)
   a  b   c   d
0  1  4  10  10
1  2  5  14  14
2  3  6  18  18

这篇关于将具有常量参数的函数应用于 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆