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

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

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

问题

只需翻译代码部分:

  1. df = pl.DataFrame(
  2. {
  3. "A": [1, 1, 1, 1, 1],
  4. 'B': [1, 2, 2, 3, 3]
  5. }
  6. )
  7. df.loc[df['B'] == 2, 'A'] = 100
  1. 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

  1. df = pl.DataFrame(
  2. {
  3. "A": [1, 1, 1, 1, 1],
  4. 'B': [1, 2, 2, 3, 3]
  5. }
  6. )
  7. 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

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

but it works only when one row met the condition.

答案1

得分: 3

你可以这样做:

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

You can do

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

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:

确定