当使用when()表达式时,如何在Python极坐标中停止otherwise()?

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

这是我的数据框:

┌─────────────────────┬──────────┐
│ date                ┆ price    │
│ ---                 ┆ ---      │
│ datetime[μs]        ┆ f64      │
╞═════════════════════╪══════════╡
│ 2023-12-20 14:10:00 ┆ 2039.105 │
│ 2023-12-21 14:45:00 ┆ 2045.795 │
│ 2023-12-22 15:10:00 ┆ 2069.708 │
│ 2023-12-26 06:45:00 ┆ 2064.885 │
│ 2023-12-27 18:00:00 ┆ 2083.865 │
│ 2023-12-28 03:05:00 ┆ 2088.224 │
│ 2023-12-28 15:00:00 ┆ 2080.245 │
│ 2023-12-29 07:10:00 ┆ 2074.485 │
└─────────────────────┴──────────┘

我的主要问题是找到彼此接近的价格并将它们分组在 Polars 中,但我没有找到任何有用的代码。所以,我决定在极地之外进行。

现在我遇到了 Polars 的问题,我想根据我单独拥有的嵌套列表对价格进行分类。我正在使用以下代码:

for i ,group in enumerate(resistance_groups):
            highs = highs.with_columns(
                pl.when(pl.col('price').is_in(group))
                    .then(i+1)
                    .otherwise(None)
                    .alias('groups')
            )

哪个抵抗组织是这样的:

[[2064.885, 2069.708, 2074.485], [2080.245, 2083.865, 2088.224]]

最高点是上面的数据框。

上述代码在第一个循环中的结果是:

┌─────────────────────┬──────────┬────────┐
│ date                ┆ price    ┆ groups │
│ ---                 ┆ ---      ┆ ---    │
│ datetime[μs]        ┆ f64      ┆ i32    │
╞═════════════════════╪══════════╪════════╡
│ 2023-12-20 14:10:00 ┆ 2039.105 ┆ null   │
│ 2023-12-21 14:45:00 ┆ 2045.795 ┆ null   │
│ 2023-12-22 15:10:00 ┆ 2069.708 ┆ 1      │
│ 2023-12-26 06:45:00 ┆ 2064.885 ┆ 1      │
│ 2023-12-27 18:00:00 ┆ 2083.865 ┆ null   │
│ 2023-12-28 03:05:00 ┆ 2088.224 ┆ null   │
│ 2023-12-28 15:00:00 ┆ 2080.245 ┆ null   │
│ 2023-12-29 07:10:00 ┆ 2074.485 ┆ 1      │
└─────────────────────┴──────────┴────────┘

在第二个循环中,它是:

┌─────────────────────┬──────────┬────────┐
│ date                ┆ price    ┆ groups │
│ ---                 ┆ ---      ┆ ---    │
│ datetime[μs]        ┆ f64      ┆ i32    │
╞═════════════════════╪══════════╪════════╡
│ 2023-12-20 14:10:00 ┆ 2039.105 ┆ null   │
│ 2023-12-21 14:45:00 ┆ 2045.795 ┆ null   │
│ 2023-12-22 15:10:00 ┆ 2069.708 ┆ null   │
│ 2023-12-26 06:45:00 ┆ 2064.885 ┆ null   │
│ 2023-12-27 18:00:00 ┆ 2083.865 ┆ 2      │
│ 2023-12-28 03:05:00 ┆ 2088.224 ┆ 2      │
│ 2023-12-28 15:00:00 ┆ 2080.245 ┆ 2      │
│ 2023-12-29 07:10:00 ┆ 2074.485 ┆ null   │
└─────────────────────┴──────────┴────────┘

如您所见,第一个循环结果已从 df 中删除。

任何人都可以建议一种方法来停止 .otherwise() 或任何其他方法来对价格列进行分类吗?

我也尝试使用多个when-then表达式,但它也不起作用, 使用另一根柱子也不是那么好。

以防万一:删除 .otherwise( ) 意味着将值设置为 null。

python dataframe python-polars
1个回答
0
投票

您需要将

highs
初始化为
groups
列全部为空,然后在
when
中添加一个
groups
为空的条件,最后更改 other 以返回自身。像这样

highs=highs.with_columns(pl.lit(None,pl.Int64).alias('groups')
for i, group in enumerate(resistance_groups):
            highs = highs.with_columns(
                pl.when((pl.col('price').is_in(group)) & pl.col('groups').is_null())
                    .then(i)
                    .otherwise(pl.col('groups'))
                    .alias('groups')
            )
© www.soinside.com 2019 - 2024. All rights reserved.