python - 如何更改 Python Polars 库中单个列的位置?

标签 python python-polars

我正在使用 Python Polars 库在 DataFrame 上进行数据操作,并且我正在尝试更改单个列的位置。我想将特定列移动到不同的索引,同时将其他列保留在各自的位置。

一种方法是使用 select,但这需要为我不想做的所有列给出完整的顺序。

import polars as pl

# Create a simple DataFrame
data = {
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9],
    'D': [10, 11, 12]
}

df = pl.DataFrame(data)

我想将“C”列移动到索引 1,因此所需的输出应该是:

shape: (3, 4)
┌─────┬─────┬─────┬──────┐
│ A   │ C   │ B   │ D    │
│ --- │ --- │ --- │ ---- │
│ i64 │ i64 │ i64 │ i64  │
╞═════╪═════╪═════╪══════╡
│ 1   │ 7   │ 4   │ 10   │
├─────┼─────┼─────┼──────┤
│ 2   │ 8   │ 5   │ 11   │
├─────┼─────┼─────┼──────┤
│ 3   │ 9   │ 6   │ 12   │
└─────┴─────┴─────┴──────┘

最佳答案

这实际上可以归结为列表损坏问题。

您可以创建此函数

def reorder(df, new_position, col_name):
    neworder=df.columns
    neworder.remove(col_name)
    neworder.insert(new_position,col_name)
    return df.select(neworder)

然后只需执行 reorder(df, 1, 'C')df=reorder(df, 1, 'C')

您甚至可以将其设为 DataFrame 方法,如下所示:

def reorder(self, new_position, col_name):
    neworder=self.columns
    neworder.remove(col_name)
    neworder.insert(new_position,col_name)
    return self.select(neworder)
pl.DataFrame.reorder=reorder
del reorder

那么你可以这样做df.reorder(1,'C')

关于python - 如何更改 Python Polars 库中单个列的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75954280/

相关文章:

python - Django AWS RDS 环境变量未在 Elastic Beanstalk 中设置

python - 有没有办法将 pl.Datetime 类型的 pl.Series 从一个时区转换为另一个时区?

python - 在 Polars Python API 中将两列组合成元组

python - 使用 python Fabric 的 Linux 机器的目录大小

python - "\"之后 sublime 中的粉红色高光

python - 如何将 Polars DataFrame 转换为 pySpark DataFrame?

python-3.x - 基于 Python Polars 列的更新不起作用

python - 查找 Polars Dataframe 的所有组合,从每一行中选择一个元素

python - Django celery redis 从队列中删除特定的周期性任务

python - 在不进行转换的情况下按字符串日期对 Pandas 数据框进行排序