Map() vs Apply() vs ApplyMap() Functions

 How do I apply a function to a Pandas Series or Data Frame?

There are 3 way to apply function.

1. Map()

Map is a series Method. Map allows you to map a existing value of a series to a different set of values.

Lets say you need to create dummy variable for Column sex.

Male, Female that is we need to translate male to 0 and female to 1.

Example: Dataframe['sex'] = Datafrmae.sex.map({'female':0,'male':1})

map will assign or map numerical values to respective strings in dictionary.


2. Apply()

Apply is a usually both series method and Data Frame method.

Apply as Series method:

It will apply a function to a each element in a series.

Example: If I want to calculate length of each string in name column,

Dataframe['Namelength'] = Dataframe.Name.apply(len)

This is Apply as a series method applying to each element in series to calculate length.

Apply as Data Frame method:

It apply a function along with either access of a Data Frame.

Example: Dataframe[: ,'name'].apply(max , axis=0)

This will apply max function vertically column wise.

when axis =1 than max function applying horizontally.


3. ApplyMap()

ApplyMap it is also a Data Frame method.

ApplyMap does is to apply a function to a every element of Data Frame.

Example: Dataframe[: ,'name'].applymap(float)

It will assign float value to every element in Data Frame.


Comments

Post a Comment