小编T.H*_*ice的帖子

将 Python 字典映射到 Polars 系列

在 Pandas 中,我们可以使用该map函数将字典映射到系列,以使用映射值创建另一个系列。更一般地说,我相信它调用参数的索引运算符,即[]

import pandas as pd

dic = { 1: 'a', 2: 'b', 3: 'c' }

pd.Series([1, 2, 3, 4]).map(dic) # returns ["a", "b", "c", NaN]
Run Code Online (Sandbox Code Playgroud)

我还没有找到直接在 Polars 中执行此操作的方法,但找到了一些替代方案。这些是否是推荐的方法,或者是否有更好的方法?

import polars as pl

dic = { 1: 'a', 2: 'b', 3: 'c' }

# Approach 1 - apply
pl.Series([1, 2, 3, 4]).apply(lambda v: dic.get(v, None)) # returns ["a", "b", "c", null]

# Approach 2 - left join
(
    pl.Series([1, 2, 3, 4])
    .alias('key')
    .to_frame()
    .join( …
Run Code Online (Sandbox Code Playgroud)

python-polars

7
推荐指数
2
解决办法
4611
查看次数

标签 统计

python-polars ×1