0

I am quite new in the data analytics/science field and have a question regarding adding a column to my pandas dataframe from a dict.

My datafram looks something like this:

data = [['LON', 9], ['PAR', 2.2], ['NYC', 8.5], ['PEK', 21.4]]

cities = pd.DataFrame(data, columns=['Code', 'Population'])

code poulation
LON 9.0
PAR 2.2
NYC 8.5
PEK 21.4

I hava a dict with the mapping of code to city name:

codes = {'LON': 'LONDON', 'PAR': 'PARIS', 'NYC': 'NEW YORK CITY', 'PEK': 'PEKING'}

And I wanna add now a column 'city' to the dataframe so it looks like this:

code poulation city
LON 9.0 LONDON
PAR 2.2 PARIS
NYC 8.5 NEW YORK CITY
PEK 21.4 PEKING

What is the best way to do this? In face I am dealing with a realy large dataset, so shoud be efficient as possible.

Thank you very much for your answer.

SimonHRD
  • 23
  • 6
  • Good question, but unfortunately it has been answered before. See the dupe. Pandas provides `pd.Series.map`: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.map.html. TLDR: `df["city"] = df["code"].map(codes)` – Chrysophylaxs Mar 14 '23 at 11:42

0 Answers0