提问人:FObersteiner 提问时间:1/16/2023 更新时间:1/16/2023 访问量:326
Python 极点:每 n 行修改一次
Python polars: modify every nth row
问:
在 Python 中给定一个极坐标数据帧,如何修改系列中的第 n 个元素?
# have
df = pl.DataFrame(pl.Series("a", [1, -1, 1, -1, 1]))
# want
# [1, 1, 1, 1, 1]
# selecting works fine:
df["a", 1::2]
shape: (2,)
Series: 'a' [i64]
[
-1
-1
]
# but modification fails:
df["a", 1::2] *= -1
Traceback (most recent call last):
File "/tmp/ipykernel_103522/957012809.py", line 1, in <cell line: 1>
df["a", 1::2] *= -1
File "/home/.../.pyenv/versions/3.10.9/lib/python3.10/site-packages/polars/internals/dataframe/frame.py", line 1439, in __setitem__
raise ValueError(f"column selection not understood: {col_selection}")
ValueError: column selection not understood: slice(1, None, 2)
pl.__version__
'0.15.14'
答:
2赞
jqurious
1/16/2023
#1
您可以添加行数并使用模运算符:
df.with_row_count().select(
pl.when((pl.col("row_nr") + 1) % 2 == 0)
.then(pl.col("a") * -1)
.otherwise(pl.col("a"))
)
shape: (5, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 1 │
├─────┤
│ 1 │
├─────┤
│ 1 │
├─────┤
│ 1 │
├─────┤
│ 1 │
└─────┘
评论
1赞
jqurious
1/17/2023
例如,有 但我认为不鼓励这种类型的索引/修改。.set_at_idx()
idx = range(1, df.height, 2); df["a"].set_at_idx(idx, df["a", idx] * -1)
评论