Polars修改符合条件的列值

本文介绍了如何在Polars库中使用`when`和`otherwise`函数根据特定条件修改DataFrame的行数据,对比了与Pandas的差异,特别提到了在循环中处理数据的方法。
摘要由CSDN通过智能技术生成

听说了polars比pandas快,今天使用了polars,然后有个需求是要修改某些符合条件的行数据,找了好多文章都没介绍这块. 后来问了AI发现一个方法,在此记录一下.

AI给的示例:

import polars as pl

df = pl.DataFrame(
    {
        "id": [0, 1, 2, 3],
        "left": [10, 11, 12, 13],
        "right": [14, 15, 16, 17],
    }
)

n = 15

# 创建条件列
df = df.with_column(pl.when(df.right < n).then(df.right + 2).otherwise(df.right))

# 过滤出符合条件的行
df = df[df.right < n]

# 设置符合条件的列的 right 为 right + 2
df = df.with_columns(
    [
        pl.col("id"),
        pl.col("left"),
        pl.col("right").alias("right_updated").when(df.right < n).then(df.right + 2),
    ]
)

print(df)

我的代码:

df = df.with_columns(
        [
            pl
            .when(pl.col('left')>start)
            .then(pl.col('left')+2)
            .otherwise(pl.col('left')),
            pl
            .when(pl.col('right')>=start)
            .then(pl.col('right')+2)
            .otherwise(pl.col('right'))
        ]
    )

这样还支持循环中修改df的值

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值