我想通过只创建一次对象,然后为每一列返回该对象的方法,一次向极点数据帧添加多列,其中每列派生自相同的对象(对于一行).以下是使用range对象的简化示例:

import polars as pl

df = pl.DataFrame({
    'x': [11, 22],
})

def uses_object(x):
    r = list(range(0, x))
    c10 = r.count(10)
    c12 = r.count(12)
    return c10, c12

df = df.with_columns(
    count_of_10 = pl.col('x').map_elements(lambda x: uses_object(x)[0]),
    count_of_12 = pl.col('x').map_elements(lambda x: uses_object(x)[1]),
)

print(df)
shape: (2, 3)
┌─────┬─────────────┬─────────────┐
│ x   ┆ count_of_10 ┆ count_of_12 │
│ --- ┆ ---         ┆ ---         │
│ i64 ┆ i64         ┆ i64         │
╞═════╪═════════════╪═════════════╡
│ 11  ┆ 1           ┆ 0           │
│ 22  ┆ 1           ┆ 1           │
└─────┴─────────────┴─────────────┘

我试过多重任务

df = df.with_columns(
    count_of_10, count_of_12 = uses_object(pl.col('x')),
)

但得到了错误

NameError
name 'count_of_10' is not defined.

我可以把密码改成只打uses_object一次吗?

推荐答案

如果从函数返回词典:

return dict(count_of_10=c10, count_of_12=c12)

您将获得一个 struct 列:

df.with_columns(
   count = pl.col('x').map_elements(uses_object)
)
shape: (2, 2)
┌─────┬───────────┐
│ x   ┆ count     │
│ --- ┆ ---       │
│ i64 ┆ struct[2] │
╞═════╪═══════════╡
│ 11  ┆ {1,0}     │
│ 22  ┆ {1,1}     │
└─────┴───────────┘

您可以将其.unnest()放入单独的列中.

df.with_columns(
   count = pl.col('x').map_elements(uses_object)
).unnest('count')
shape: (2, 3)
┌─────┬─────────────┬─────────────┐
│ x   ┆ count_of_10 ┆ count_of_12 │
│ --- ┆ ---         ┆ ---         │
│ i64 ┆ i64         ┆ i64         │
╞═════╪═════════════╪═════════════╡
│ 11  ┆ 1           ┆ 0           │
│ 22  ┆ 1           ┆ 1           │
└─────┴─────────────┴─────────────┘

至于您当前的方法,您将调用它一次,然后使用Polar List方法来提取单独的.with_columns/.select中的值.

df.with_columns(
   count = pl.col('x').map_elements(uses_object)
).with_columns(
   count_of_10 = pl.col('count').list.first(),
   count_of_12 = pl.col('count').list.last(),
).drop('count')

Python相关问答推荐

从webhook中的短代码(而不是电话号码)接收Twilio消息

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

为什么tkinter框架没有被隐藏?

难以在Manim中正确定位对象

如何让Flask 中的请求标签发挥作用

按顺序合并2个词典列表

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

Telethon加入私有频道

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

从嵌套的yaml创建一个嵌套字符串,后面跟着点

名为__main__. py的Python模块在导入时不运行'

Polars asof在下一个可用日期加入

如何更改groupby作用域以找到满足掩码条件的第一个值?

基于行条件计算(pandas)

Flask运行时无法在Python中打印到控制台

根据Pandas中带条件的两个列的值创建新列

如何在Python中自动创建数字文件夹和正在进行的文件夹?

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

如何关联来自两个Pandas DataFrame列的列表项?

在不中断格式的情况下在文件的特定部分插入XML标签