|
4 | 4 | registered by `register_verb` and should be placed in `./verbs.py` |
5 | 5 | """ |
6 | 6 | import itertools |
7 | | -from typing import Any, Callable, Iterable, Union |
| 7 | +from typing import Any, Callable, Iterable, List, Union |
8 | 8 | import numpy |
9 | 9 |
|
10 | 10 | import pandas |
11 | 11 | from pandas import Categorical, DataFrame |
12 | 12 | from pipda import register_func |
13 | 13 |
|
14 | 14 | from ..core.middlewares import WithDataEnv |
15 | | -from ..core.types import NumericType |
| 15 | +from ..core.types import NumericType, is_scalar |
16 | 16 | from ..core.contexts import Context |
| 17 | +from ..core.names import repair_names |
17 | 18 |
|
18 | 19 |
|
19 | 20 | @register_func(None, context=Context.EVAL) |
@@ -131,3 +132,48 @@ def data_context(data: DataFrame) -> Any: |
131 | 132 | The original or modified data |
132 | 133 | """ |
133 | 134 | return WithDataEnv(data) |
| 135 | + |
| 136 | +def make_names(names: Any, unique: bool = False) -> List[str]: |
| 137 | + """Make names available as columns and can be accessed by `df.<name>` |
| 138 | +
|
| 139 | + The names will be transformed using `python-slugify` with |
| 140 | + `lowercase=False` and `separator="_"`. When the first character is |
| 141 | + a digit, preface it with "_". |
| 142 | +
|
| 143 | + If `unique` is True, the results will be fed into |
| 144 | + `datar.core.names.repair_names(names, "unique")` |
| 145 | +
|
| 146 | + Args: |
| 147 | + names: The names |
| 148 | + if it is scalar, will make it into a list. |
| 149 | + Then all elements will be converted into strings |
| 150 | + unique: Whether to make the names unique |
| 151 | +
|
| 152 | + Returns: |
| 153 | + Converted names |
| 154 | + """ |
| 155 | + from slugify import slugify |
| 156 | + from . import as_character |
| 157 | + if is_scalar(names): |
| 158 | + names = [names] |
| 159 | + names = as_character(names) |
| 160 | + names = [slugify(name, separator="_", lowercase=False) for name in names] |
| 161 | + names = [f"_{name}" if name[0].isdigit() else name for name in names] |
| 162 | + if unique: |
| 163 | + return repair_names(names, "unique") |
| 164 | + return names |
| 165 | + |
| 166 | +def make_unique(names: Any) -> List[str]: |
| 167 | + """Make the names unique. |
| 168 | +
|
| 169 | + It's a shortcut for `make_names(names, unique=True)` |
| 170 | +
|
| 171 | + Args: |
| 172 | + names: The names |
| 173 | + if it is scalar, will make it into a list. |
| 174 | + Then all elements will be converted into strings |
| 175 | +
|
| 176 | + Returns: |
| 177 | + Converted names |
| 178 | + """ |
| 179 | + return make_names(names, unique=True) |
0 commit comments