英文:
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 │
└─────┴─────┘
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论