Data Wrangling with Python Datatable - Replicate Pandas’ Map Function

Data Wrangling with Python Datatable - Replicate Pandas’ Map Function#

Complete Solution#

m = df["city"]
m.replace(city_to_state)

df["state"] = m
df
first_namelast_nameagecitystate
▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
0JasonMiller42San FranciscoCalifornia
1MollyJacobson52BaltimoreMaryland
2TinaAli36MiamiFlorida
3JakeMilner24DouglasArizona
4AmyCooze73BostonMassachusetts

Breakdown of Solution#

Step 1: Create a temporary dataframe to hold the values in city.

m = df['city']
m
city
▪▪▪▪
0San Francisco
1Baltimore
2Miami
3Douglas
4Boston

Step 2: Replace the values in m with city_to_state, by using the replace function. Note that the replace function does not require assignment, as the computation is done inplace:

m.replace(city_to_state)
m
city
▪▪▪▪
0California
1Maryland
2Florida
3Arizona
4Massachusetts

Step 3: Assign m to new column state in df:

df["state"] = m
df
first_namelast_nameagecitystate
▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪▪
0JasonMiller42San FranciscoCalifornia
1MollyJacobson52BaltimoreMaryland
2TinaAli36MiamiFlorida
3JakeMilner24DouglasArizona
4AmyCooze73BostonMassachusetts

Comments#