Python 极坐标:修改每第 n 行

问题描述 投票:0回答:1

给定 Python 中的极坐标 DataFrame,如何修改系列中的每个第 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'

问题的熊猫版本

python indexing slice python-polars
1个回答
2
投票

您可以添加行索引并使用模运算:

(df.with_row_index()
   .with_columns(
      pl.when((pl.col("index") + 1) % 2 == 0)
        .then(pl.col("a") * -1)
        .otherwise(pl.col("a"))
   )
)
shape: (5, 2)
┌───────┬─────┐
│ index ┆ a   │
│ ---   ┆ --- │
│ u32   ┆ i64 │
╞═══════╪═════╡
│ 0     ┆ 1   │
│ 1     ┆ 1   │
│ 2     ┆ 1   │
│ 3     ┆ 1   │
│ 4     ┆ 1   │
└───────┴─────┘
© www.soinside.com 2019 - 2024. All rights reserved.