python - 将一列值分配给极性Python中的另一列

标签 python python-3.x python-polars

在极地 Pandas 中,想要在两行中相互更改/分配和相互更改行值。

for i in range(len(k2)):
    k2['column1'][i] == k2['column2'][i]
    k2['column3'][i] == k2['column4'][i]

最佳答案

您可以使用别名来复制和重命名列:

import polars as pl

k2 = pl.DataFrame({"column1": [1,2,3],
                   "column2": [4,5,6],
                   "column3": [7,8,9],
                   "column4": [10,11,12]})

┌─────────┬─────────┬─────────┬─────────┐
│ column1 ┆ column2 ┆ column3 ┆ column4 │
│ ---     ┆ ---     ┆ ---     ┆ ---     │
│ i64     ┆ i64     ┆ i64     ┆ i64     │
╞═════════╪═════════╪═════════╪═════════╡
│ 1       ┆ 4       ┆ 7       ┆ 10      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 2       ┆ 5       ┆ 8       ┆ 11      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 3       ┆ 6       ┆ 9       ┆ 12      │
└─────────┴─────────┴─────────┴─────────┘
k2.with_columns([pl.col("column2").alias("column1"), pl.col("column4").alias("column3")])

打印出

┌─────────┬─────────┬─────────┬─────────┐
│ column1 ┆ column2 ┆ column3 ┆ column4 │
│ ---     ┆ ---     ┆ ---     ┆ ---     │
│ i64     ┆ i64     ┆ i64     ┆ i64     │
╞═════════╪═════════╪═════════╪═════════╡
│ 4       ┆ 4       ┆ 10      ┆ 10      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 5       ┆ 5       ┆ 11      ┆ 11      │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 6       ┆ 6       ┆ 12      ┆ 12      │
└─────────┴─────────┴─────────┴─────────┘

关于python - 将一列值分配给极性Python中的另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71631720/

相关文章:

python - 如何robuSTLy检索python环境的bin路径?

django - 我如何将最近保存的数据发送到 django 中同一 View 函数中的模板中

python - 如何使用 "condense"长递归 Polars 表达式?

python-polars - 在Python中,极性将json字符串列转换为字典以进行过滤

python - 矩阵每行包含特定数字

python - 简明地说 "none of the elements of an array are None"?

python - 如何返回匹配某些文本的正则表达式?

python - Polars/Python 限制打印表输出行数

使用 Firefox geckodriver 的绝对路径时,Python Selenium 测试不会运行

Python re.findall 仅返回第一个字符