Difference between Map, Apply and Applymap in Pandas

pandas
map
apply
applymap
python

#1

Hi,

Please help me with an example to know the difference between Map, Apply and Applymap in Python Pandas? Also guide, when should I use which one?

Regards,
Imran


#2

@Imran,

These are techniques to apply function to element, column or dataframe.

Map: It iterates over each element of a series.
df[‘column1’].map(lambda x: 10+x), this will add 10 to each element of column1.
df[‘column2’].map(lambda x: ‘AV’+x), this will concatenate “AV“ at the beginning of each element of column2 (column format is string).

Apply: As the name suggests, applies a function along any axis of the DataFrame.
df[[‘column1’,’column2’]].apply(sum), it will returns the sum of all the values of column1 and column2.

ApplyMap: This helps to apply a function to each element of dataframe.
func = lambda x: x+2
df.applymap(func), it will add 2 to each element of dataframe (all columns of dataframe must be numeric type)

Regards,
Mark