rename

pydiverse.transform.rename(name_map: dict[str, str]) Pipeable[source]

Renames columns.

Parameters:

name_map – A dictionary assigning some columns new names.

Examples

Renaming one column:

>>> t = pdt.Table({"a": [3, 2, 6, 4], "b": ["lll", "g", "u0", "__**_"]})
>>> t >> rename({"a": "h"}) >> show()
shape: (4, 2)
┌─────┬───────┐
│ h   ┆ b     │
│ --- ┆ ---   │
│ i64 ┆ str   │
╞═════╪═══════╡
│ 3   ┆ lll   │
│ 2   ┆ g     │
│ 6   ┆ u0    │
│ 4   ┆ __**_ │
└─────┴───────┘

Here is a more subtle example: As long as there are no two equal column names in the result table, one can give names to columns that already exist in the table. In the following example, the names of columns a and b are swapped.

>>> s = t >> rename({"a": "b", "b": "a"}) >> show()
Table <unnamed>, backend: PolarsImpl
shape: (4, 2)
┌─────┬───────┐
│ b   ┆ a     │
│ --- ┆ ---   │
│ i64 ┆ str   │
╞═════╪═══════╡
│ 3   ┆ lll   │
│ 2   ┆ g     │
│ 6   ┆ u0    │
│ 4   ┆ __**_ │
└─────┴───────┘

When using the column t.a in an expression derived from s now, it still refers to the same column, which now has the name b. The anonymous column C.a, however, refers to the column with name a in the current table.

>>> s >> mutate(u=t.a, v=C.a) >> show()
shape: (4, 4)
┌─────┬───────┬─────┬───────┐
│ b   ┆ a     ┆ u   ┆ v     │
│ --- ┆ ---   ┆ --- ┆ ---   │
│ i64 ┆ str   ┆ i64 ┆ str   │
╞═════╪═══════╪═════╪═══════╡
│ 3   ┆ lll   ┆ 3   ┆ lll   │
│ 2   ┆ g     ┆ 2   ┆ g     │
│ 6   ┆ u0    ┆ 6   ┆ u0    │
│ 4   ┆ __**_ ┆ 4   ┆ __**_ │
└─────┴───────┴─────┴───────┘