如何使用 groupby 并应用到 polars

How to use groupby and apply with polars

我正在绞尽脑汁想弄清楚如何在 Python 的库 polars 中使用 groupbyapply

来自 Pandas,我正在使用:

def get_score(df):
   return spearmanr(df["prediction"], df["target"]).correlation

correlations = df.groupby("era").apply(get_score)

但在极地,这不起作用。

我尝试了几种方法,主要围绕:

correlations = df.groupby("era").apply(get_score)

但这失败并显示错误消息:

'Could net get DataFrame attribute '_df'. Make sure that you return a DataFrame object.: PyErr { type: <class 'AttributeError'>, value: AttributeError("'numpy.float64' object has no attribute '_df'"),

有什么想法吗?

polars>=0.10.4 开始,您可以使用 pl.spearman_rank_corr 函数。

如果你想使用自定义函数,你可以这样做:

多个自定义函数 columns/expressions

import polars as pl
from typing import List
from scipy import stats

df = pl.DataFrame({
    "g": [1, 1, 1, 2, 2, 2, 5],
    "a": [2, 4, 5, 190, 1, 4, 1],
    "b": [1, 3, 2, 1, 43, 3, 1]
})

def get_score(args: List[pl.Series]) -> pl.Series:
    return pl.Series([stats.spearmanr(args[0], args[1]).correlation], dtype=pl.Float64)

(df.groupby("g", maintain_order=True)
 .agg(
    pl.apply(
        exprs=["a", "b"], 
        f=get_score).alias("corr")
 ))

Polars 提供的功能

(df.groupby("g", maintain_order=True)
 .agg(
     pl.spearman_rank_corr("a", "b").alias("corr")
 ))

两者输出:

shape: (3, 2)
┌─────┬──────┐
│ g   ┆ corr │
│ --- ┆ ---  │
│ i64 ┆ f64  │
╞═════╪══════╡
│ 1   ┆ 0.5  │
├╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2   ┆ -1e0 │
├╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 5   ┆ NaN  │
└─────┴──────┘

单个 column/expression

上的自定义函数

我们还可以通过 .apply.map 对单个表达式应用自定义函数。

下面是一个示例,说明我们如何使用自定义函数和普通极坐标表达式对列进行平方。表达式语法 应该始终是首选,因为它要快得多。

(df.groupby("g")
 .agg(
     pl.col("a").apply(lambda group: group**2).alias("squared1"),
     (pl.col("a")**2).alias("squared2")
 ))

applymap 有什么区别?

map 适用于整列 seriesapply 适用于单个值或单个组,具体取决于上下文。

select 上下文:
  • map
    • input/output 类型:Series
    • 输入的语义:一列值
  • apply
    • input/output 类型:Union[int, float, str, bool]
    • 输入的语义:列中的单个值
groupby 上下文:
  • map
    • input/output 类型:Series
    • 输入的语义含义:值为组的列表列
  • apply
    • input/output 类型:Series
    • 输入的语义:组