使用 Polars 根据另一列的条件修改某列的一些行。

huangapple go评论59阅读模式
英文:

Modify some rows of one column based on conditions from another column using Polars

问题

只需翻译代码部分:

df = pl.DataFrame(
    {
    "A": [1, 1, 1, 1, 1],
    'B': [1, 2, 2, 3, 3]
    }
)

df.loc[df['B'] == 2, 'A'] = 100
df[df['B'] == 2, 'A'] = 100

不适用于多行满足条件的情况。

英文:

Given the data frame below, I would need to modify column 'A' using conditions of 'B'. Pandas expression for that is presented with .loc

df = pl.DataFrame(
    {
    "A": [1, 1, 1, 1, 1],
    'B': [1, 2, 2, 3, 3]
    }
)

df.loc[df['B'] == 2, 'A'] = 100

I have a big data set and I need to do this a lot of times for small samples. I know that it is possible to solve with apply function by going through all rows, but I need a fast solution, O(1) if possible, instead of O(n).
I tried to use

df[df['B'] == 2, 'A'] = 100

but it works only when one row met the condition.

答案1

得分: 3

你可以这样做:

In [9]: df.with_columns(A=pl.when(pl.col('B')==2).then(100).otherwise(pl.col('A')))
Out[9]:
shape: (5, 2)
┌─────┬─────┐
 A    B   
 ---  --- 
 i64  i64 
╞═════╪═════╡
 1    1   
 100  2   
 100  2   
 1    3   
 1    3   
└─────┴─────┘
英文:

You can do

In [9]: df.with_columns(A=pl.when(pl.col('B')==2).then(100).otherwise(pl.col('A')))
Out[9]:
shape: (5, 2)
┌─────┬─────┐
 A    B   
 ---  --- 
 i64  i64 
╞═════╪═════╡
 1    1   
 100  2   
 100  2   
 1    3   
 1    3   
└─────┴─────┘

huangapple
  • 本文由 发表于 2023年2月23日 21:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定