When to use apply
Note: the following are copied from this stackoverflow page
The following shows the performances of different approaches to converting a dataframe of 2 date columns stored in object (i.e. string) format into datetime format.
import pandas as pd
print(f'pandas version: {pd.__version__}')
pandas version: 1.3.4
##construct a dataframe
df = pd.DataFrame(data = {'abbr':['A', 'B', 'C'], 'val':[1, 2, 3]})
df
abbr | val | |
---|---|---|
0 | A | 1 |
1 | B | 2 |
2 | C | 3 |
#use map
map_dict = {'A':'Apple', 'B':'Banana', 'C': 'Cherry'}
df['fullname']=df['abbr'].map(map_dict)
df
abbr | val | fullname | |
---|---|---|---|
0 | A | 1 | Apple |
1 | B | 2 | Banana |
2 | C | 3 | Cherry |
#use apply
df['name_len']=df['fullname'].apply(lambda x:len(x))
df
abbr | val | fullname | name_len | |
---|---|---|---|---|
0 | A | 1 | Apple | 5 |
1 | B | 2 | Banana | 6 |
2 | C | 3 | Cherry | 6 |
#use apply
df['print_out'] = df[['abbr', 'val']].apply(lambda x:f'{x["abbr"]}:{x["val"]}', axis=1)
df
abbr | val | fullname | name_len | print_out | |
---|---|---|---|---|---|
0 | A | 1 | Apple | 5 | A:1 |
1 | B | 2 | Banana | 6 | B:2 |
2 | C | 3 | Cherry | 6 | C:3 |
#use applymap
df['val_pow2']=df[['val']].applymap(lambda x: x**2)['val']
df
abbr | val | fullname | name_len | print_out | val_pow2 | |
---|---|---|---|---|---|---|
0 | A | 1 | Apple | 5 | A:1 | 1 |
1 | B | 2 | Banana | 6 | B:2 | 4 |
2 | C | 3 | Cherry | 6 | C:3 | 9 |