考虑一些像这样的 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)
但是我应该考虑其他方法来减少重复吗?
由于您不需要任何原始列,因此可以使用
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"]
)