yoshiserry
yoshiserry

Reputation: 21395

how do you map a pandas dataframe column to a function which requires more than one parameter

I have a function which has two arguments, the first argument is some text the second a regex pattern.

I want to pass each row of a certain column from my dataframe to a function using .map however I am not sure how to direct the data from the dataframe to be the first argument and the regex (which will be the same pattern for each row) to be the second argument?

def regex(pattern,text):
    p = pattern
    t = str(text)
    results = re.findall(p,t)
    return results

df['new_column'] = df['source_code'].map(some_function)

Upvotes: 1

Views: 270

Answers (1)

jezrael
jezrael

Reputation: 863791

I think you need lambda function with parameters pattern and x:

df['new_column'] = df['source_code'].map(lambda x: some_function(pattern, x))

df['new_column'] = df['source_code'].apply(lambda x: some_function(pattern, x))

Thank you Jon Clements for another solution:

df['new_column'] = df['source_code'].apply(some_function, args=(pattern ,x)) 

Upvotes: 1

Related Questions