简体   繁体   English

Python Pandas:如何使用.apply()将两个或多个参数/列值传递给自定义函数

[英]Python Pandas: How to pass two or more arguments/ column-values to a custom function using .apply ()

数据集如下所示

I am trying to write a custom function which takes 3 inputs and is basically checking the length of Full Name(First+Last) > Occupation.I have tries 2 variations of apply but both are giving an error. 我正在尝试编写一个自定义函数,该函数需要3个输入,并且基本上是在检查Full Name(First + Last)> Occupation的长度。我尝试了2个apply的变体,但都给出了错误。 PS I am rookie in Python and Pandas area. PS我是Python和Pandas地区的新手。

def check(fname,lname,occu):
if(len(fname)+len(lname)>len(occu)):
    return True
else:
    return False

customers.apply(lambda x: check(x['First Name'],x['Last Name'],x['Occupation']),axis=1)

错误 错误的另一个变化

The immediate error is probably a typo, ie you need len(lname) rather than lname(lname) . 即时错误可能是拼写错误,即您需要len(lname)而不是lname(lname) But you don't need a row-wise loop. 但是您不需要逐行循环。 You can call pd.Series.str.len instead: 您可以改为调用pd.Series.str.len

df['CheckFlag'] = (df['First Name'].str.len() + df['Last Name'].str.len()) > \
                  df['Occupation'].str.len()

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

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