python polars有np.where等价物吗



Polars有np.where等价物吗?尝试在polar中复制以下代码。如果该值高于某个阈值,则称为is_Acceptable的列为1,或者如果低于该值,则为0

import pandas as pd
import numpy as np 
df = pd.DataFrame({"fruit":["orange","apple","mango","kiwi"], "value":[1,0.8,0.7,1.2]})
df["Is_Acceptable?"] = np.where(df["value"].lt(0.9), 1, 0)
print(df)

是的,有pl.when().then().otherwise()表达式

import polars as pl
from polars import col
df = pl.DataFrame({
"fruit": ["orange","apple","mango","kiwi"],
"value": [1, 0.8, 0.7, 1.2]
})
df = df.with_column(
pl.when(col('value') < 0.9).then(1).otherwise(0).alias('Is_Acceptable?')
)
print(df)
┌────────┬───────┬────────────────┐
│ fruit  ┆ value ┆ Is_Acceptable? │
│ ---    ┆ ---   ┆ ---            │
│ str    ┆ f64   ┆ i64            │
╞════════╪═══════╪════════════════╡
│ orange ┆ 1.0   ┆ 0              │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ apple  ┆ 0.8   ┆ 1              │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ mango  ┆ 0.7   ┆ 1              │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ kiwi   ┆ 1.2   ┆ 0              │
└────────┴───────┴────────────────┘

when/then/otherwise表达式是一个很好的通用答案。然而,在这种情况下,一个快捷方式是简单地创建一个布尔表达式。

(
df
.with_column(
(pl.col('value') < 0.9).alias('Is_Acceptable')
)
)
shape: (4, 3)
┌────────┬───────┬───────────────┐
│ fruit  ┆ value ┆ Is_Acceptable │
│ ---    ┆ ---   ┆ ---           │
│ str    ┆ f64   ┆ bool          │
╞════════╪═══════╪═══════════════╡
│ orange ┆ 1.0   ┆ false         │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ apple  ┆ 0.8   ┆ true          │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ mango  ┆ 0.7   ┆ true          │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ kiwi   ┆ 1.2   ┆ false         │
└────────┴───────┴───────────────┘

在数值计算中,False将上变频为0True将上变频至1。或者,如果您愿意,可以将它们显式上转换为不同的类型。

(
df
.with_column(
(pl.col('value') < 0.9).cast(pl.Int64).alias('Is_Acceptable')
)
)
shape: (4, 3)
┌────────┬───────┬───────────────┐
│ fruit  ┆ value ┆ Is_Acceptable │
│ ---    ┆ ---   ┆ ---           │
│ str    ┆ f64   ┆ i64           │
╞════════╪═══════╪═══════════════╡
│ orange ┆ 1.0   ┆ 0             │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ apple  ┆ 0.8   ┆ 1             │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ mango  ┆ 0.7   ┆ 1             │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ kiwi   ┆ 1.2   ┆ 0             │
└────────┴───────┴───────────────┘

最新更新