October 24, 2024
Chicago 12, Melborne City, USA
python

Create new column in df based on membership of values from another column in a dictionary


Python 3.12.3
Polars 1.8.2
Polars-lts-cpu: 1.10.0
OS: Linux-lite 24.04 VM

I have the following code:

import polars as pl

countries = ['usa', 'france', 'brazil']
calling_codes = [1, 33, 55]

df = pl.DataFrame({'country': countries, 'calling_code': calling_codes })

capitals_dict = {'usa':'washington_dc', 'france': 'paris', 'brazil': 'brasilia'}

I would like to create a new column called capital in df that gets filled from the values in capitals_dict if the country that is found in df['country'] is in the keys of capitals_dict. I’m not entirely sure if that makes sense, so I can write some pseudo-code or something if that’s easier.

I have tried using filter, replace, with_columns, and map_elements but have thus far been unsuccessful. I have only known about polars for a few days so I apologize for the simple question. Any help is much appreciated!



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video