根据字典中另一列的值的成员资格在 df 中创建新列

问题描述 投票:0回答:1

Python 3.12.3 极地1.8.2 极地-lts-cpu:1.10.0 操作系统:Linux-lite 24.04 虚拟机

我有以下代码:

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'}

我想在

capital
中创建一个名为
df
的新列,如果
capitals_dict
中找到的国家/地区位于
df['country']
的键中,则该列将从
capitals_dict
中的值填充。我不完全确定这是否有意义,所以我可以编写一些伪代码或其他更容易的东西。

我尝试过使用

filter
replace
with_columns
map_elements
,但迄今为止尚未成功。我才知道
polars
几天,所以我为这个简单的问题道歉。非常感谢任何帮助!

python python-polars
1个回答
0
投票

这是您需要使用的 DataFrames.join() 方法。我抓住了你的代码,这就是我的想法:

>>> import polars as pl

>>> countries = ["usa", "france", "brazil"]
>>> calling_codes = [1, 33, 55]
>>> capitals = ["washington_dc", "paris", "brasilia"]

>>> df = pl.DataFrame({'country': countries, 'calling_code': calling_codes })
>>> df
shape: (3, 2)
┌─────────┬──────────────┐
│ country ┆ calling_code │
│ ---     ┆ ---          │
│ str     ┆ i64          │
╞═════════╪══════════════╡
│ usa     ┆ 1            │
│ france  ┆ 33           │
│ brazil  ┆ 55           │
└─────────┴──────────────┘

>>> df_capitals = pl.DataFrame({"country": countries, "capital": capitals})
>>> df.join(df_capitals, on='country')
shape: (3, 3)
┌─────────┬──────────────┬───────────────┐
│ country ┆ calling_code ┆ capital       │
│ ---     ┆ ---          ┆ ---           │
│ str     ┆ i64          ┆ str           │
╞═════════╪══════════════╪═══════════════╡
│ usa     ┆ 1            ┆ washington_dc │
│ france  ┆ 33           ┆ paris         │
│ brazil  ┆ 55           ┆ brasilia      │
└─────────┴──────────────┴───────────────┘

您也可以这样创建

df_capitals

>>> capitals = {"usa": "washington_dc", "france": "paris", "brazil": "brasilia"}
>>> df_capitals =  pl.DataFrame({"country": capitals.keys(), "capital": capitals.values()})
>>> df_capitals
shape: (3, 2)
┌─────────┬───────────────┐
│ country ┆ capital       │
│ ---     ┆ ---           │
│ str     ┆ str           │
╞═════════╪═══════════════╡
│ usa     ┆ washington_dc │
│ france  ┆ paris         │
│ brazil  ┆ brasilia      │
└─────────┴───────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.