极坐标使用 Expression API 与 DataFrame 的行

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

我是新的

polars
用户,我想在每个
polars DataFrame
行中应用一个函数。在
pandas
中,我将使用
apply
函数,指定函数的输入是
DataFrame
的行而不是
DataFrame
的列。

我看到了 Polars 库的

apply
函数,它说最好使用 Expression API,而不是在 Polars
apply
上使用
DataFrame
函数,因为效率更高。该文档提供了带有
select
函数的表达式 API 示例,但
select
DataFrames
的列一起使用。有没有办法将表达式 API 与
DataFrame
的行一起使用?

编辑提供示例

我有一个具有这种结构的

DataFrame

l=[(1,2,3,4,22,23,None,None),(5,6,8,10,None,None,None,None)]
df=pl.DataFrame(data=l, orient='row')

即a

DataFrame
在某个时刻直到最后,一行有
None
值。在此示例中,在第一行中,
None
值从第 6 列开始,而在第二行中,
None
值从第 4 列开始。

我想做的是找到最有效的极坐标方法,将这个

DataFrame
变成只有三列的
DataFrame
,其中第一列是该行的第一个元素,第二列是该行的第二个元素行,第三行将列出以下列中不属于
None
的所有其他元素。

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

如果您使用列名称,您可以:

df.select(
   pl.col("column_0", "column_1"), 
   pl.concat_list(pl.exclude("column_0", "column_1"))
     .list.drop_nulls()
)
shape: (2, 3)
┌──────────┬──────────┬──────────────┐
│ column_0 ┆ column_1 ┆ column_2     │
│ ---      ┆ ---      ┆ ---          │
│ i64      ┆ i64      ┆ list[i64]    │
╞══════════╪══════════╪══════════════╡
│ 1        ┆ 2        ┆ [3, 4, … 23] │
│ 5        ┆ 6        ┆ [8, 10]      │
└──────────┴──────────┴──────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.