如何改变Python极地库中单列的位置?



我正在使用Python polar库对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   │
└─────┴─────┴─────┴──────┘

一些尝试:

df.drop("C").insert_at_idx(1, df.get_column("C"))
df.select(df.columns[0], "C", pl.exclude(df.columns[0], "C"))
cols = df.columns
cols[1], cols[2] = cols[2], cols[1]
# cols[1:3] = cols[2:0:-1]
df.select(cols)
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')