Polars:在列名称中搜索和替换:是否可以使用 LazyFrames?

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

已回答的问题的后续内容,是否可以在 LazyFrame 中搜索和替换列名称?我这样做是作为一种解决方法(基于 ritchie46 的链接答案,谢谢!):

df = df.lazy().collect()
df.columns = list(map(lambda x: x.replace("Total", ""), df.columns)) 
python lazy-evaluation python-polars
2个回答
1
投票

还有

pl.LazyFrame.rename

import polars as pl

df = pl.LazyFrame({
    "Total_foo": [1],
    "bar_Total": [2],
    "other": [3],
})

df.rename(lambda name: name.replace("Total", "")).collect()
shape: (1, 3)
┌──────┬──────┬───────┐
│ _foo ┆ bar_ ┆ other │
│ ---  ┆ ---  ┆ ---   │
│ i64  ┆ i64  ┆ i64   │
╞══════╪══════╪═══════╡
│ 1    ┆ 2    ┆ 3     │
└──────┴──────┴───────┘

1
投票
(pl.LazyFrame({
    "Total_foo": [1],
    "bar_Total": [2],
    "other": [3],
}).select(
     pl.all().name.map(lambda name: name.replace("Total", ""))
)).collect()

shape: (1, 3)
┌──────┬──────┬───────┐
│ _foo ┆ bar_ ┆ other │
│ ---  ┆ ---  ┆ ---   │
│ i64  ┆ i64  ┆ i64   │
╞══════╪══════╪═══════╡
│ 1    ┆ 2    ┆ 3     │
└──────┴──────┴───────┘
© www.soinside.com 2019 - 2024. All rights reserved.