4

Say I have a certain mapping:

mapping = {
    'cat': 'purrfect',
    'dog': 'too much work',
    'fish': 'meh'
    }

and a dataframe:

    animal  name       description
0   cat     sparkles   NaN
1   dog     rufus      NaN
2   fish    mr. blub   NaN

I would like to programmatically fill in the description column using the animal column and mapping dict as inputs:

def describe_pet(animal,mapping):
    return mapping[animal]

When I try to use pandas apply() function:

df['description'].apply(describe_pet,args=(df['animal'],mapping))

I get the following error:

TypeError: describe_pet() takes exactly 2 arguments (3 given)

It seems like using apply() is trivial passing one argument to the function. How can I do it with two arguments?

ryantuck
  • 6,146
  • 10
  • 57
  • 71

2 Answers2

6

You can do this with the map method without writing a function or using apply at all:

df['description'] = df.animal.map(mapping)
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • that is very elegant and is certainly best for my particular situation. Ophir Yoktan's answer applies to the more general question. – ryantuck Jun 13 '15 at 20:01
2

The suggested answer solves your specific problem, but for the more generic case:

The args parameter is for parameters in addition to the columns:

args : tuple Positional arguments to pass to function in addition to the array/series

pandas.DataFrame.apply

Ophir Yoktan
  • 8,149
  • 7
  • 58
  • 106