user3682157
user3682157

Reputation: 1695

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

Say I have a DF defined as variable 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?

EDIT: Ubuntu's answer is what I would normally use but I need to self reference the DF in my function

Upvotes: 0

Views: 890

Answers (1)

unutbu
unutbu

Reputation: 879143

You could use the Series.apply method:

df1['Words'].apply(func)

If you wish to pass more positional arguments to func, use the args keyword parameter:

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

or, to pass df as a keyword argument:

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

since, per the docs, "[a]dditional keyword arguments [to apply] will be passed as keywords to the function".

Upvotes: 1

Related Questions