我正在阅读一个CSV文件,需要规范化列名,作为更大的函数链接操作的一部分.我想用函数链接来做一切.
当使用推荐的name.map
函数替换列中的字符时,如:
import polars as pl
df = pl.DataFrame(
{"A (%)": [1, 2, 3], "B": [4, 5, 6], "C (Euro)": ["abc", "def", "ghi"]}
).with_columns(
pl.all().name.map(
lambda c: c.replace(" ", "_")
.replace("(%)", "pct")
.replace("(Euro)", "euro")
.lower()
)
)
df.head()
我得到
shape: (3, 6)
┌───────┬─────┬──────────┬───────┬─────┬────────┐
│ A (%) ┆ B ┆ C (Euro) ┆ a_pct ┆ b ┆ c_euro │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str ┆ i64 ┆ i64 ┆ str │
╞═══════╪═════|══════════╡═══════╡═════╡════════╡
│ 1 ┆ 4 ┆ "abc" ┆ 1 ┆ 4 ┆ "abc" │
│ 2 ┆ 5 ┆ "def" ┆ 2 ┆ 5 ┆ "def" │
│ 3 ┆ 6 ┆ "ghi" ┆ 3 ┆ 6 ┆"ghi" │
└───────┴─────┴──────────┴───────┴─────┴────────┘
而不是预期的
shape: (3, 3)
┌───────┬─────┬────────┐
│ a_pct ┆ b ┆ c_euro │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═══════╪═════|════════╡
│ 1 ┆ 4 ┆ "abc" │
│ 2 ┆ 5 ┆ "def" │
│ 3 ┆ 6 ┆ "ghi" │
└───────┴─────┴────────┘
?
How can I replace specific chars in existing column names with function chaining without creating new columns?