简体   繁体   English

将变量名传递给函数的参数(Python 3,Pandas)

[英]Pass a Variable Name to the Arguments of a Function (Python 3, Pandas)

Say I have a DF defined as variable DF1: 假设我有一个DF定义为变量DF1:

  Words         Score
  The man        10
  A Plan         20
  Panama         30

And say I have a function: 并说我有一个功能:

def func(w, df):
   pattern = re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE)
if pattern.search(df):
    return True
else:
    return False

How do I pass each row of DF1, specifically the columns 'Words', to the argument within the function? 如何将DF1的每一行(特别是“单词”列)传递给函数中的参数?

EDIT: Ubuntu's answer is what I would normally use but I need to self reference the DF in my function 编辑:Ubuntu的答案是我通常使用的,但是我需要在函数中自引用DF

You could use the Series.apply method : 您可以使用Series.apply方法

df1['Words'].apply(func)

If you wish to pass more positional arguments to func , use the args keyword parameter: 如果希望将更多的位置参数传递给func ,请使用args关键字参数:

df1['Words'].apply(func, args=(df,))

or, to pass df as a keyword argument: 或者,将df作为关键字参数传递:

df1['Words'].apply(func, df=df)

since, per the docs , "[a]dditional keyword arguments [to apply ] will be passed as keywords to the function" . 因为, 根据文档“ [要apply ] [a] dditional关键字参数将作为关键字传递给函数”

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

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