import polars as pl
url = "https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv"
df = pl.read_csv(url)
change = (
df.with_columns(pl.col("sepal_width").shift(1, fill_value=0).pct_change(1).alias("pct_1"))
.with_columns(
pl.when(pl.col("pct_1").is_infinite())
.then(float(0))
.otherwise(pl.col("pct_1"))
.fill_null(float(0))
.name.keep(),
pl.col("pct_1").cum_sum().alias("cumsum_pct_1")
)
)
给定一个数据集,我想在使用 pct_change 后计算 cumsum。但即使填充后,结果也是无效的。已经搜索了一段时间了。请有人帮助我。
现在:
┌──────────────┬─────────────┬──────────────┬─────────────┬───────────┬───────────┬──────────────┐
│ sepal_length ┆ sepal_width ┆ petal_length ┆ petal_width ┆ species ┆ pct_1 ┆ cumsum_pct_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 ┆ str ┆ f64 ┆ f64 │
╞══════════════╪═════════════╪══════════════╪═════════════╪═══════════╪═══════════╪══════════════╡
│ 5.1 ┆ 3.5 ┆ 1.4 ┆ 0.2 ┆ setosa ┆ 0.0 ┆ null │
│ 4.9 ┆ 3.0 ┆ 1.4 ┆ 0.2 ┆ setosa ┆ 0.0 ┆ inf │
│ 4.7 ┆ 3.2 ┆ 1.3 ┆ 0.2 ┆ setosa ┆ -0.142857 ┆ inf │
│ 4.6 ┆ 3.1 ┆ 1.5 ┆ 0.2 ┆ setosa ┆ 0.066667 ┆ inf │
预期:
┌──────────────┬─────────────┬──────────────┬─────────────┬───────────┬───────────┬──────────────┐
│ sepal_length ┆ sepal_width ┆ petal_length ┆ petal_width ┆ species ┆ pct_1 ┆ cumsum_pct_1 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 ┆ str ┆ f64 ┆ f64 │
╞══════════════╪═════════════╪══════════════╪═════════════╪═══════════╪═══════════╪══════════════╡
│ 5.1 ┆ 3.5 ┆ 1.4 ┆ 0.2 ┆ setosa ┆ 0.0 ┆ 0.0 │
│ 4.9 ┆ 3.0 ┆ 1.4 ┆ 0.2 ┆ setosa ┆ 0.0 ┆ 0.0 │
│ 4.7 ┆ 3.2 ┆ 1.3 ┆ 0.2 ┆ setosa ┆ -0.142857 ┆ -0.142857 │
│ 4.6 ┆ 3.1 ┆ 1.5 ┆ 0.2 ┆ setosa ┆ 0.066667 ┆ -0.076190 │
我认为你遇到的问题是对表达式在上下文中如何工作的一个小误解(“with_columns”)。上下文中的所有表达式并行运行,因此一列的更改对其他表达式不可见。因此,要解决您的问题,您必须明智地进行
change = (
df.with_columns(
(pl.col("sepal_width").shift_and_fill(1, 0).pct_change(1).alias("pct_1"))
)
.with_columns(
[
pl.when(pl.col("pct_1").is_infinite())
.then(float(0))
.otherwise(pl.col("pct_1"))
.fill_null(float(0))
.keep_name()
]
)
.with_columns([pl.col("pct_1").cumsum().alias("cumsum_pct_1")])
)
另请参阅这个问题