使用 Polars 时减少代码/表达式重复?

问题描述 投票:0回答:1

考虑一些像这样的 Polars 代码:

df.with_columns(
    pl.date_ranges(
        pl.col("current_start"), pl.col("current_end"), "1mo", closed="left"
    ).alias("current_tpoints")
).drop("current_start", "current_end").with_columns(
    pl.date_ranges(
        pl.col("history_start"), pl.col("history_end"), "1mo", closed="left"
    ).alias("history_tpoints")
).drop(
    "history_start", "history_end"
)

这里要注意的关键问题是

history_*
current_*
的重复性。我可以通过这样做减少重复:

for x in ["history", "current"]:
    fstring = f"{x}" + "_{other}"
    start = fstring.format(other="start")
    end = fstring.format(other="end")
    df = df.with_columns(
        pl.date_ranges(
            pl.col(start),
            pl.col(end),
            "1mo",
            closed="left",
        ).alias(fstring.format(other="tpoints"))
    ).drop(start, end)

但是我应该考虑其他方法来减少重复吗?

python python-polars
1个回答
0
投票

由于您不需要任何原始列,因此可以使用

select()
代替
with_columns()

您可以在 select 中循环列名称:

df.select(
    pl.date_ranges(
        pl.col(f"{c}_start"), pl.col(f"{c}_end"), "1mo", closed="left"
    ).alias(f"{c}_tpoints") for c in ["current", "history"]
)
© www.soinside.com 2019 - 2024. All rights reserved.