python - Apply function to column in pandas dataframe that takes two arguments -
say have mapping:
mapping = { 'cat': 'purrfect', 'dog': 'too work', 'fish': 'meh' }
and dataframe
:
animal name description 0 cat sparkles nan 1 dog rufus nan 2 fish mr. blub nan
i programmatically fill in description
column using animal
column , mapping
dict inputs:
def describe_pet(animal,mapping): return mapping[animal]
when try use pandas apply()
function:
df['description'].apply(describe_pet,args=(df['animal'],mapping))
i following error:
typeerror: describe_pet() takes 2 arguments (3 given)
it seems using apply()
trivial passing 1 argument function. how can 2 arguments?
the suggested answer solves specific problem, more generic case:
the args
parameter parameters in addition columns:
args : tuple positional arguments pass function in addition array/series
Comments
Post a Comment