这曾经是pandas这样处理的:
df.columns = df.columns.str.replace('.','_')
Run Code Online (Sandbox Code Playgroud)
这段代码可以工作,但绝对不是正确的解决方案。
renamed = {}
for column_name in list(filter(lambda x: '.' in x, df.columns)):
renamed[column_name] = column_name.replace('.', '_')
df = df.rename(renamed)
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以使用Polars.Expr.map_alias,它将给定的函数应用于每个列名称。它对于重命名方法链中的列特别有用。
\nimport polars as pl\n\ndf = pl.DataFrame({\n \'col.a\': [1, 2],\n \'col.b\': [3, 2]\n})\n\nres = df.select(\n pl.all().map_alias(lambda col_name: col_name.replace(\'.\', \'_\'))\n)\nRun Code Online (Sandbox Code Playgroud)\n输出:
\n>>> res\n\nshape: (2, 2)\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 col_a \xe2\x94\x86 col_b \xe2\x94\x82\n\xe2\x94\x82 --- \xe2\x94\x86 --- \xe2\x94\x82\n\xe2\x94\x82 i64 \xe2\x94\x86 i64 \xe2\x94\x82\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 1 \xe2\x94\x86 3 \xe2\x94\x82\n\xe2\x94\x82 2 \xe2\x94\x86 2 \xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\nRun Code Online (Sandbox Code Playgroud)\n
df.columns返回一个 pythonList[str]并且它也支持__setitem__,所以你可以在这里使用 python 。
df = pl.DataFrame({\n "a.c": [1, 2],\n "b.d": [3, 4]\n})\ndf.columns = list(map(lambda x: x.replace(".", "_"), df.columns))\nprint(df)\nRun Code Online (Sandbox Code Playgroud)\nshape: (2, 2)\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xac\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n\xe2\x94\x82 a_c \xe2\x94\x86 b_d \xe2\x94\x82\n\xe2\x94\x82 --- \xe2\x94\x86 --- \xe2\x94\x82\n\xe2\x94\x82 i64 \xe2\x94\x86 i64 \xe2\x94\x82\n\xe2\x95\x9e\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xaa\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa1\n\xe2\x94\x82 1 \xe2\x94\x86 3 \xe2\x94\x82\n\xe2\x94\x9c\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x94\xbc\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x95\x8c\xe2\x94\xa4\n\xe2\x94\x82 2 \xe2\x94\x86 4 \xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xb4\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\n\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
10933 次 |
| 最近记录: |