主要数据框如下:
test = pl.DataFrame(
{
"date": ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05"],
"value": [1, 2, 3, 4, 5],
}
).with_row_index().with_columns(pl.col("date").cast(pl.Date))
print(test)
out:
shape: (5, 3)
┌───────┬────────────┬───────┐
│ index ┆ date ┆ value │
│ --- ┆ --- ┆ --- │
│ u32 ┆ date ┆ i64 │
╞═══════╪════════════╪═══════╡
│ 0 ┆ 2020-01-01 ┆ 1 │
│ 1 ┆ 2020-01-02 ┆ 2 │
│ 2 ┆ 2020-01-03 ┆ 3 │
│ 3 ┆ 2020-01-04 ┆ 4 │
│ 4 ┆ 2020-01-05 ┆ 5 │
└───────┴────────────┴───────┘
我想找到另一个形状为 (1, 1) 的数据帧之前的第一个索引:
shape: (1, 1)
┌────────────┐
│ date │
│ --- │
│ date │
╞════════════╡
│ 2020-01-04 │
└────────────┘
预期输出:2或“2020-01-03”
首先,您可以使用
other
获取数据框中的日期 datetime.date
作为 pl.DataFrame.item()
。
other.item()
datetime.date(2020, 1, 4)
我们可以使用它来过滤主数据帧,然后选择过滤后的数据帧中的最后一行。
(
test
.filter(
pl.col("date") < other.item()
)
.select(
pl.col("index").last()
)
.item()
)
2
注意。 如果您想要相应的
date
值 datetime.date(2020, 1, 3)
,您可以类似地选择 date
列。