[英]How to perform an elementwise maximum of two columns in a Python polars expression?
如何計算表達式內 Polars 中兩列的元素最大值?
極地版本 = 0.13.31
問題陳述作為代碼:
import polars as pl
import numpy as np
df = pl.DataFrame({
"a": np.arange(5),
"b": np.arange(5)[::-1]
})
# Produce a column with the values [4, 3, 2, 3, 4] using df.select([ ... ]).alias("max(a, b)")
Polars 聲稱支持 numpy 通用函數( docs ),其中包括 np.maximum ,它可以滿足我的要求。 但是,當我嘗試時,我得到一個錯誤。
df.select([
np.maximum(pl.col("a"), pl.col("b")).alias("max(a, b)")
])
# TypeError: maximum() takes from 2 to 3 positional arguments but 1 were given
似乎沒有為此內置 Polars,有pl.max
但這僅返回數組中的單個最大元素。
使用.map()
my_df.select([
pl.col(["a", "b"]).map(np.maximum)
])
# PanicException
我可以使用以下代碼段執行此操作,但是我希望能夠在表達式中執行此操作,因為它更方便。
df["max(a, b)"] = np.maximum(df["a"], df["b"])
你很親密。 polars.max
與Expressions 列表一起使用時,將返回按元素計算的最大值。 從文檔中:
List[Expr] -> 橫向聚合最大值。
因此,對於您的示例:
df.with_column(
pl.max([pl.col('a'), pl.col('b')]).alias('max(a, b)')
)
shape: (5, 3)
┌─────┬─────┬───────────┐
│ a ┆ b ┆ max(a, b) │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═══════════╡
│ 0 ┆ 4 ┆ 4 │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 1 ┆ 3 ┆ 3 │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 2 ┆ 2 ┆ 2 │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 3 ┆ 1 ┆ 3 │
├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 4 ┆ 0 ┆ 4 │
└─────┴─────┴───────────┘
作為參考,當提供表達式列表時, polars.min
、 polars.sum
、 polars.any
和polars.all
也將執行元素計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.