pycraftbox-dataframe 4.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pycraftbox/dataframe/__init__.py +16 -0
- pycraftbox/dataframe/cleaners.py +143 -0
- pycraftbox/dataframe/converters.py +503 -0
- pycraftbox/dataframe/helpers.py +30 -0
- pycraftbox/dataframe/mapper.py +929 -0
- pycraftbox_dataframe-4.0.0.dist-info/METADATA +10 -0
- pycraftbox_dataframe-4.0.0.dist-info/RECORD +8 -0
- pycraftbox_dataframe-4.0.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Pandas and CSV utilities."""
|
|
2
|
+
|
|
3
|
+
from .cleaners import Cleaners
|
|
4
|
+
from .converters import Converters
|
|
5
|
+
from .helpers import PandasHelpers
|
|
6
|
+
from .mapper import ColDefinition, ColMapping, CompiledMapping, DFFileMapper
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Cleaners",
|
|
10
|
+
"ColDefinition",
|
|
11
|
+
"ColMapping",
|
|
12
|
+
"CompiledMapping",
|
|
13
|
+
"Converters",
|
|
14
|
+
"DFFileMapper",
|
|
15
|
+
"PandasHelpers",
|
|
16
|
+
]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Utilities for cleaning and repairing malformed tabular data.
|
|
2
|
+
|
|
3
|
+
This module hosts the :class:`Cleaners` class, which provides helpers used
|
|
4
|
+
while reading CSV files, such as repairing lines with unescaped quotes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import uuid
|
|
11
|
+
from typing import Callable
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Cleaners:
|
|
15
|
+
"""Utility class providing methods for cleaning and repairing malformed data."""
|
|
16
|
+
|
|
17
|
+
_logger: logging.Logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def pick_separator(cls, fields: list[str]) -> str:
|
|
21
|
+
"""Pick a rare separator character not present in any of the fields.
|
|
22
|
+
|
|
23
|
+
This method tries a list of rare control characters first, then falls
|
|
24
|
+
back to generating a unique token if none of the control characters
|
|
25
|
+
are suitable.
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
fields: List of field strings to check for separator conflicts.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
A separator string that doesn't appear in any field.
|
|
32
|
+
|
|
33
|
+
Example::
|
|
34
|
+
|
|
35
|
+
fields = ["Hello, world", "Test data"]
|
|
36
|
+
sep = Cleaners.pick_separator(fields)
|
|
37
|
+
"""
|
|
38
|
+
candidates = ["\x1f", "\x1e", "\x1d", "\x1c", "\x00"] # rare control chars
|
|
39
|
+
for c in candidates:
|
|
40
|
+
if all(c not in f for f in fields):
|
|
41
|
+
return c
|
|
42
|
+
|
|
43
|
+
# fallback: token long et unique
|
|
44
|
+
while True:
|
|
45
|
+
token = f"__SEP_{uuid.uuid4().hex}__"
|
|
46
|
+
if all(token not in f for f in fields):
|
|
47
|
+
return token
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def repair_bad_line(
|
|
51
|
+
cls, expected_cols: int
|
|
52
|
+
) -> Callable[[list[str]], list[str] | None]:
|
|
53
|
+
"""Return a callback for pandas on_bad_lines that repairs malformed CSV lines.
|
|
54
|
+
|
|
55
|
+
This method creates a callback function that can be passed to pandas
|
|
56
|
+
``read_csv()`` via the ``on_bad_lines`` parameter. The callback attempts
|
|
57
|
+
to repair lines with unescaped quotes inside quoted fields by properly
|
|
58
|
+
escaping them.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
expected_cols: The expected number of columns in the CSV file.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
A callable that accepts a list of field strings and returns either
|
|
65
|
+
a repaired list of the expected length, or ``None`` if the line
|
|
66
|
+
cannot be repaired.
|
|
67
|
+
|
|
68
|
+
Example::
|
|
69
|
+
|
|
70
|
+
# Use with pandas read_csv
|
|
71
|
+
repair_fn = Cleaners.repair_bad_line(expected_cols=12)
|
|
72
|
+
df = pd.read_csv(
|
|
73
|
+
"data.csv",
|
|
74
|
+
engine="python",
|
|
75
|
+
on_bad_lines=repair_fn,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
Note:
|
|
79
|
+
This callback is designed for use with the Python engine only
|
|
80
|
+
(``engine='python'``). The C engine does not support custom
|
|
81
|
+
``on_bad_lines`` callbacks.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def _repair(fields: list[str]) -> list[str] | None:
|
|
85
|
+
"""Internal callback that repairs a malformed line.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
fields: List of field strings from the malformed line.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
A list of exactly expected_cols fields if repair succeeds,
|
|
92
|
+
None otherwise.
|
|
93
|
+
"""
|
|
94
|
+
sep = cls.pick_separator(fields)
|
|
95
|
+
quote = '"'
|
|
96
|
+
out = []
|
|
97
|
+
in_quoted_segment = False
|
|
98
|
+
i = 0
|
|
99
|
+
line = sep.join(fields)
|
|
100
|
+
n = len(line)
|
|
101
|
+
|
|
102
|
+
while i < n:
|
|
103
|
+
ch = line[i]
|
|
104
|
+
if ch != quote:
|
|
105
|
+
out.append(ch)
|
|
106
|
+
i += 1
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
# if not in quoted segment we are on an opening quote, we just add it and move on
|
|
110
|
+
if not in_quoted_segment:
|
|
111
|
+
in_quoted_segment = True
|
|
112
|
+
out.append(ch)
|
|
113
|
+
i += 1
|
|
114
|
+
continue
|
|
115
|
+
|
|
116
|
+
# we are on a quote and inside a quoted segment, next char can tell us if it's a closing quote,
|
|
117
|
+
# an escaped quote OR a quote that need to be escaped.
|
|
118
|
+
nxt = line[i + 1] if i + 1 < n else ""
|
|
119
|
+
|
|
120
|
+
# Test if it's an escaped quote, if yes we add it and move on
|
|
121
|
+
if nxt == quote:
|
|
122
|
+
out.append(quote)
|
|
123
|
+
out.append(quote)
|
|
124
|
+
i += 2
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
# Test if it's a closing quote, if yes we add it and move on
|
|
128
|
+
if nxt in (sep, "\n", "\r", ""):
|
|
129
|
+
in_quoted_segment = False
|
|
130
|
+
out.append(ch)
|
|
131
|
+
i += 1
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
# This is an unquoted quote inside a quoted segment, we need to escape it by doubling it
|
|
135
|
+
out.append(quote)
|
|
136
|
+
out.append(quote)
|
|
137
|
+
i += 1
|
|
138
|
+
|
|
139
|
+
res = "".join(out)
|
|
140
|
+
splits = res.split(sep)
|
|
141
|
+
return splits if len(splits) == expected_cols else None
|
|
142
|
+
|
|
143
|
+
return _repair
|
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
"""Column value converters for :mod:`pycraftbox.dataframe`.
|
|
2
|
+
|
|
3
|
+
This module hosts the :class:`Converters` factory class, which produces the
|
|
4
|
+
callables used to normalize, parse, and transform raw cell values while
|
|
5
|
+
reading tabular data into pandas DataFrames.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from pandas._libs.tslibs.nattype import NaTType
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Converters:
|
|
23
|
+
"""Provide factory methods and orchestration for column value converters.
|
|
24
|
+
|
|
25
|
+
:class:`DFFileMapper` automatically protects every configured conversion
|
|
26
|
+
chain from missing-value markers. Processing follows this fixed order:
|
|
27
|
+
|
|
28
|
+
1. Strip leading and trailing whitespace when requested by
|
|
29
|
+
:attr:`ColDefinition.strip` or :attr:`ColMapping.strip_all`.
|
|
30
|
+
2. Normalize recognized NA markers through :meth:`_na_safe`.
|
|
31
|
+
3. Invoke the boolean or user-provided converters in their declared order.
|
|
32
|
+
|
|
33
|
+
NA normalization short-circuits the chain, so a recognized marker becomes
|
|
34
|
+
``np.nan`` and is never passed to a user converter. Users therefore do not
|
|
35
|
+
need to add NA checks to their converters. Running strip first also allows
|
|
36
|
+
a value such as ``" MISSING "`` to match ``"MISSING"`` in
|
|
37
|
+
:attr:`ColDefinition.na_values` or :attr:`ColMapping.na_values`.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
_logger: logging.Logger = logging.getLogger(__name__)
|
|
41
|
+
|
|
42
|
+
NUMBER_SPACES: frozenset[str] = frozenset(
|
|
43
|
+
{" ", "\u00a0", "\u2007", "\u2009", "\u202f"}
|
|
44
|
+
)
|
|
45
|
+
"""Spaces commonly used as thousands separators in formatted numbers."""
|
|
46
|
+
|
|
47
|
+
# The default NA sentinel strings recognized by pandas.read_csv when
|
|
48
|
+
# keep_default_na is True (mirrors pandas' own default na_values list).
|
|
49
|
+
DEFAULT_NA_VALUES: frozenset[str] = frozenset(
|
|
50
|
+
{
|
|
51
|
+
"",
|
|
52
|
+
"#N/A",
|
|
53
|
+
"#N/A N/A",
|
|
54
|
+
"#NA",
|
|
55
|
+
"-1.#IND",
|
|
56
|
+
"-1.#QNAN",
|
|
57
|
+
"-NaN",
|
|
58
|
+
"-nan",
|
|
59
|
+
"1.#IND",
|
|
60
|
+
"1.#QNAN",
|
|
61
|
+
"<NA>",
|
|
62
|
+
"N/A",
|
|
63
|
+
"NA",
|
|
64
|
+
"NULL",
|
|
65
|
+
"NaN",
|
|
66
|
+
"None",
|
|
67
|
+
"n/a",
|
|
68
|
+
"nan",
|
|
69
|
+
"null",
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def _na_safe(
|
|
75
|
+
cls,
|
|
76
|
+
value: Any,
|
|
77
|
+
na_values: Iterable[str] = (),
|
|
78
|
+
keep_default_na: bool = True,
|
|
79
|
+
) -> Any:
|
|
80
|
+
"""Normalize a recognized NA value before column converters run.
|
|
81
|
+
|
|
82
|
+
Pandas does not replace raw input markers before invoking a configured
|
|
83
|
+
converter. The mapper calls this method after optional whitespace
|
|
84
|
+
stripping and before the first boolean or user-provided converter.
|
|
85
|
+
Returning ``np.nan`` causes the remaining conversion chain to be
|
|
86
|
+
skipped.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
value: Raw value received from pandas.
|
|
90
|
+
na_values: Extra NA marker strings to recognize, typically the
|
|
91
|
+
merged :attr:`ColMapping.na_values` and
|
|
92
|
+
:attr:`ColDefinition.na_values` declared for the column.
|
|
93
|
+
keep_default_na: When ``True`` (the default), pandas' own default
|
|
94
|
+
NA marker strings (:attr:`DEFAULT_NA_VALUES`) are also
|
|
95
|
+
recognized, mirroring pandas' ``keep_default_na`` behaviour.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
``np.nan`` for a recognized NA value, otherwise the original value.
|
|
99
|
+
"""
|
|
100
|
+
na_set: set[str] = set(na_values)
|
|
101
|
+
if keep_default_na:
|
|
102
|
+
na_set |= cls.DEFAULT_NA_VALUES
|
|
103
|
+
|
|
104
|
+
if value is None:
|
|
105
|
+
return np.nan
|
|
106
|
+
if isinstance(value, float) and pd.isna(value):
|
|
107
|
+
return np.nan
|
|
108
|
+
if str(value).strip() in na_set:
|
|
109
|
+
return np.nan
|
|
110
|
+
return value
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def get_bool_convertor(cls, value: str) -> Callable[[Any], bool]:
|
|
114
|
+
"""Return a convertor that maps cell values to booleans.
|
|
115
|
+
|
|
116
|
+
The convertor returns ``True`` when the cell value (stripped and
|
|
117
|
+
lowercased) starts with the provided *value* key, and ``False``
|
|
118
|
+
otherwise. The comparison is case-insensitive and leading/trailing
|
|
119
|
+
whitespace is ignored.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
value: The string prefix that represents ``True``
|
|
123
|
+
(e.g. ``"yes"`` matches ``"Yes"``, ``"YES"``, ``"yes indeed"``).
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
A callable that accepts a raw cell value and returns a ``bool``.
|
|
127
|
+
|
|
128
|
+
Example::
|
|
129
|
+
|
|
130
|
+
# Create a boolean converter for "yes" values
|
|
131
|
+
bool_conv = Converters.get_bool_convertor("yes")
|
|
132
|
+
|
|
133
|
+
# Use in ColDefinition
|
|
134
|
+
col_def = ColDefinition(
|
|
135
|
+
file_col_name="Active",
|
|
136
|
+
df_col_name="is_active",
|
|
137
|
+
df_col_type=bool,
|
|
138
|
+
df_col_convertor=bool_conv,
|
|
139
|
+
)
|
|
140
|
+
"""
|
|
141
|
+
test = value.strip().lower()
|
|
142
|
+
return lambda x: x is not None and str(x).strip().lower().startswith(test)
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def get_date_converter(
|
|
146
|
+
cls, date_format: str = "%Y-%m-%d %H:%M:%S"
|
|
147
|
+
) -> Callable[[Any], pd.Timestamp | NaTType]:
|
|
148
|
+
"""Return a converter that parses dates or timestamps to pandas Timestamp.
|
|
149
|
+
|
|
150
|
+
The converter handles various input types:
|
|
151
|
+
- String dates/timestamps matching the specified format
|
|
152
|
+
- Existing datetime/Timestamp objects
|
|
153
|
+
- Missing values (None, empty strings, NaN)
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
date_format: The expected format of date strings to parse.
|
|
157
|
+
Default is "%Y-%m-%d %H:%M:%S".
|
|
158
|
+
Examples:
|
|
159
|
+
- "%Y-%m-%d %H:%M:%S" for "2025-01-15 14:30:00"
|
|
160
|
+
- "%d-%m-%Y %H:%M:%S" for "15-01-2025 14:30:00"
|
|
161
|
+
- "%Y-%m-%d" for "2025-01-15"
|
|
162
|
+
- "%d/%m/%Y" for "15/01/2025"
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
A callable that accepts a raw cell value and returns a pd.Timestamp.
|
|
166
|
+
Returns pd.NaT for invalid or missing values.
|
|
167
|
+
|
|
168
|
+
Example::
|
|
169
|
+
|
|
170
|
+
# Create a date converter for European format
|
|
171
|
+
date_conv = Converters.get_date_converter("%d-%m-%Y %H:%M:%S")
|
|
172
|
+
|
|
173
|
+
# Use in ColDefinition
|
|
174
|
+
col_def = ColDefinition(
|
|
175
|
+
file_col_name="Transaction Date",
|
|
176
|
+
df_col_name="date",
|
|
177
|
+
df_col_type=object,
|
|
178
|
+
df_col_convertor=date_conv,
|
|
179
|
+
)
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def _convert(x: Any) -> pd.Timestamp | NaTType:
|
|
183
|
+
# Handle missing values
|
|
184
|
+
if pd.isna(x) or x == "":
|
|
185
|
+
return pd.NaT
|
|
186
|
+
|
|
187
|
+
# If already a Timestamp, return as-is
|
|
188
|
+
if isinstance(x, pd.Timestamp):
|
|
189
|
+
return x
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
return pd.to_datetime(x, format=date_format)
|
|
193
|
+
except (ValueError, TypeError) as e:
|
|
194
|
+
cls._logger.warning(
|
|
195
|
+
f"Failed to parse date '{x}' with format '{date_format}': {e}"
|
|
196
|
+
)
|
|
197
|
+
return pd.NaT
|
|
198
|
+
|
|
199
|
+
return _convert
|
|
200
|
+
|
|
201
|
+
@classmethod
|
|
202
|
+
def get_regex_transformer(
|
|
203
|
+
cls,
|
|
204
|
+
pattern: str,
|
|
205
|
+
transformer: Callable[[re.Match], Any],
|
|
206
|
+
default: Any = None,
|
|
207
|
+
flags: int = 0,
|
|
208
|
+
) -> Callable[[Any], Any]:
|
|
209
|
+
r"""Return a converter that transforms text values using regex pattern matching.
|
|
210
|
+
|
|
211
|
+
This method creates a converter function that applies a regex pattern to
|
|
212
|
+
input values and transforms them using a custom function. Useful for
|
|
213
|
+
extracting and converting specific patterns from text data.
|
|
214
|
+
|
|
215
|
+
Args:
|
|
216
|
+
pattern: Regular expression pattern to match against input values.
|
|
217
|
+
transformer: Callable that receives a ``re.Match`` object and returns
|
|
218
|
+
the transformed value. The Match object contains captured groups
|
|
219
|
+
that can be accessed via ``.group(0)``, ``.group(1)``, etc.
|
|
220
|
+
default: Value to return when the pattern doesn't match or when the
|
|
221
|
+
input is missing/empty. If ``None``, returns the original value
|
|
222
|
+
unchanged.
|
|
223
|
+
flags: Optional regex flags (e.g., ``re.IGNORECASE``,
|
|
224
|
+
``re.MULTILINE``).
|
|
225
|
+
|
|
226
|
+
Returns:
|
|
227
|
+
A callable that accepts a raw cell value and returns a transformed
|
|
228
|
+
value.
|
|
229
|
+
|
|
230
|
+
Example::
|
|
231
|
+
|
|
232
|
+
# Extract percentage and convert to decimal
|
|
233
|
+
percent_conv = Converters.get_regex_transformer(
|
|
234
|
+
r"(\d+(?:\.\d+)?)%",
|
|
235
|
+
lambda m: float(m.group(1)) / 100.0,
|
|
236
|
+
default=0.0
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Extract currency amount (format: 1 234,56 €)
|
|
240
|
+
currency_conv = Converters.get_regex_transformer(
|
|
241
|
+
r"([\d\s,]+(?:\.\d{2})?)?\s*€",
|
|
242
|
+
lambda m: float(m.group(1).replace(" ", "").replace(",", ".")),
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
# Extract and clean ISIN code (remove text in parentheses)
|
|
246
|
+
isin_conv = Converters.get_regex_transformer(
|
|
247
|
+
r"^([A-Z]{2}[A-Z0-9]{10})",
|
|
248
|
+
lambda m: m.group(1),
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
# Use in ColDefinition
|
|
252
|
+
col_def = ColDefinition(
|
|
253
|
+
file_col_name="Percentage",
|
|
254
|
+
df_col_name="percentage",
|
|
255
|
+
df_col_type=float,
|
|
256
|
+
df_col_convertor=percent_conv,
|
|
257
|
+
)
|
|
258
|
+
"""
|
|
259
|
+
compiled_pattern = re.compile(pattern, flags)
|
|
260
|
+
|
|
261
|
+
def _transform(x: Any) -> Any:
|
|
262
|
+
# Handle missing values
|
|
263
|
+
if pd.isna(x) or x == "":
|
|
264
|
+
return default if default is not None else x
|
|
265
|
+
|
|
266
|
+
s = str(x)
|
|
267
|
+
match = compiled_pattern.search(s)
|
|
268
|
+
|
|
269
|
+
if match:
|
|
270
|
+
try:
|
|
271
|
+
return transformer(match)
|
|
272
|
+
except (ValueError, TypeError, AttributeError) as e:
|
|
273
|
+
cls._logger.warning(
|
|
274
|
+
f"Failed to transform value '{x}' using pattern '{pattern}': {e}"
|
|
275
|
+
)
|
|
276
|
+
return default if default is not None else x
|
|
277
|
+
|
|
278
|
+
# No match found
|
|
279
|
+
return default if default is not None else x
|
|
280
|
+
|
|
281
|
+
return _transform
|
|
282
|
+
|
|
283
|
+
@classmethod
|
|
284
|
+
def get_number_converter(
|
|
285
|
+
cls, thousand_sep: str | Iterable[str] = "", decimal_sep: str = "."
|
|
286
|
+
) -> Callable[[Any], Any]:
|
|
287
|
+
"""Return a converter that normalizes localized number strings.
|
|
288
|
+
|
|
289
|
+
Numbers written with locale-specific thousand and decimal separators
|
|
290
|
+
(e.g. ``"1.234,56"`` in French/German notation) cannot be parsed
|
|
291
|
+
directly by Python's numeric constructors. This converter strips the
|
|
292
|
+
thousand separator and replaces the decimal separator with a plain
|
|
293
|
+
dot (``"."``), producing a string that ``float()`` or ``int()`` (and
|
|
294
|
+
pandas' own type casting) can parse directly (e.g. ``"1234.56"``).
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
thousand_sep: The thousand separator used in the source data
|
|
298
|
+
(e.g. ``" "``, ``"."``, ``","``), or an iterable of separators
|
|
299
|
+
to remove. Pass :attr:`NUMBER_SPACES` to accept common Unicode
|
|
300
|
+
spacing variants: space (``U+0020``), no-break space
|
|
301
|
+
(``U+00A0``), figure space (``U+2007``), thin space
|
|
302
|
+
(``U+2009``), and narrow no-break space (``U+202F``). Pass an
|
|
303
|
+
empty string (the default) if the source has no thousand
|
|
304
|
+
separator.
|
|
305
|
+
decimal_sep: The decimal separator character used in the source
|
|
306
|
+
data. Defaults to ``"."``, which is already Python-compatible
|
|
307
|
+
and left untouched.
|
|
308
|
+
|
|
309
|
+
Returns:
|
|
310
|
+
A callable that accepts a raw cell value and returns a string
|
|
311
|
+
with normalized separators, ready to be cast via ``float()`` or
|
|
312
|
+
``int()``. Missing/empty values are returned unchanged.
|
|
313
|
+
|
|
314
|
+
Note:
|
|
315
|
+
To also remove currency symbols, percentage signs, or other stray
|
|
316
|
+
characters, combine this converter with
|
|
317
|
+
:meth:`get_sign_striping_conveter` by passing both as a list to
|
|
318
|
+
``df_col_convertor`` — :class:`ColDefinition` chains them
|
|
319
|
+
automatically. **List order matters:** put this converter
|
|
320
|
+
**first**, since :meth:`get_sign_striping_conveter` looks for a
|
|
321
|
+
literal ``"."`` to recognize the decimal point. The decimal
|
|
322
|
+
separator must be normalized to ``"."`` before the sign is
|
|
323
|
+
stripped; listing them in the reverse order will truncate or
|
|
324
|
+
corrupt the fractional part whenever *decimal_sep* is not already
|
|
325
|
+
``"."``.
|
|
326
|
+
|
|
327
|
+
Example::
|
|
328
|
+
|
|
329
|
+
# French format: "1.234,56" -> "1234.56"
|
|
330
|
+
num_conv = Converters.get_number_converter(thousand_sep=".", decimal_sep=",")
|
|
331
|
+
|
|
332
|
+
# Accept regular, non-breaking, thin, and narrow non-breaking spaces
|
|
333
|
+
num_conv = Converters.get_number_converter(
|
|
334
|
+
thousand_sep=Converters.NUMBER_SPACES,
|
|
335
|
+
decimal_sep=",",
|
|
336
|
+
)
|
|
337
|
+
num_conv("1\u202f234,56") # -> "1234.56"
|
|
338
|
+
|
|
339
|
+
col_def = ColDefinition(
|
|
340
|
+
file_col_name="Montant",
|
|
341
|
+
df_col_name="amount",
|
|
342
|
+
df_col_type=float,
|
|
343
|
+
df_col_convertor=num_conv,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
# Combined with get_sign_striping_conveter (correct order):
|
|
347
|
+
# "1.234,56 €" -> "1234.56 €" -> "1234.56"
|
|
348
|
+
col_def = ColDefinition(
|
|
349
|
+
file_col_name="Montant",
|
|
350
|
+
df_col_name="amount",
|
|
351
|
+
df_col_type=float,
|
|
352
|
+
df_col_convertor=[
|
|
353
|
+
Converters.get_number_converter(thousand_sep=".", decimal_sep=","),
|
|
354
|
+
Converters.get_sign_striping_conveter(),
|
|
355
|
+
],
|
|
356
|
+
)
|
|
357
|
+
"""
|
|
358
|
+
|
|
359
|
+
thousand_separators = (
|
|
360
|
+
(thousand_sep,) if isinstance(thousand_sep, str) else tuple(thousand_sep)
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
def _convert(x: Any) -> Any:
|
|
364
|
+
# Handle missing values
|
|
365
|
+
if pd.isna(x) or x == "":
|
|
366
|
+
return x
|
|
367
|
+
|
|
368
|
+
s = str(x)
|
|
369
|
+
for separator in thousand_separators:
|
|
370
|
+
if separator:
|
|
371
|
+
s = s.replace(separator, "")
|
|
372
|
+
if decimal_sep and decimal_sep != ".":
|
|
373
|
+
s = s.replace(decimal_sep, ".")
|
|
374
|
+
return s
|
|
375
|
+
|
|
376
|
+
return _convert
|
|
377
|
+
|
|
378
|
+
@classmethod
|
|
379
|
+
def get_sign_striping_conveter(cls) -> Callable[[Any], Any]:
|
|
380
|
+
r"""Return a converter that strips non-numeric symbols around a number.
|
|
381
|
+
|
|
382
|
+
Removes currency symbols, percentage signs, spaces, or any other
|
|
383
|
+
characters found before or after the numeric part of a value (e.g.
|
|
384
|
+
``"1234.56 €"``, ``"$1234.56"``, ``"45%"``), keeping only the
|
|
385
|
+
optional leading sign, digits, and decimal point so the result can be
|
|
386
|
+
cast to a number by Python's ``float()`` or ``int()``.
|
|
387
|
+
|
|
388
|
+
Returns:
|
|
389
|
+
A callable that accepts a raw cell value and returns a numeric
|
|
390
|
+
string (optional sign, digits, and at most one decimal point).
|
|
391
|
+
Missing/empty values are returned unchanged; if no numeric
|
|
392
|
+
pattern is found, the original string is returned unchanged.
|
|
393
|
+
|
|
394
|
+
Note:
|
|
395
|
+
This converter assumes the decimal point is already a literal
|
|
396
|
+
``"."``. When the source data uses locale-specific separators
|
|
397
|
+
(e.g. ``"1.234,56 €"``), combine it with
|
|
398
|
+
:meth:`get_number_converter` by passing both as a list to
|
|
399
|
+
``df_col_convertor`` — :class:`ColDefinition` chains them
|
|
400
|
+
automatically. **List order matters:** put
|
|
401
|
+
:meth:`get_number_converter` **first** to normalize the
|
|
402
|
+
separators before this converter strips the sign. Listing them
|
|
403
|
+
in the reverse order will truncate the fractional part, because
|
|
404
|
+
the regex used here would stop at the first non-``"."``
|
|
405
|
+
character it encounters (e.g. a thousand separator or comma).
|
|
406
|
+
|
|
407
|
+
Example::
|
|
408
|
+
|
|
409
|
+
strip_conv = Converters.get_sign_striping_conveter()
|
|
410
|
+
|
|
411
|
+
col_def = ColDefinition(
|
|
412
|
+
file_col_name="Montant",
|
|
413
|
+
df_col_name="amount",
|
|
414
|
+
df_col_type=float,
|
|
415
|
+
df_col_convertor=strip_conv,
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
strip_conv("1234.56 €") # -> "1234.56"
|
|
419
|
+
strip_conv("$-45.10") # -> "-45.10"
|
|
420
|
+
strip_conv("45%") # -> "45"
|
|
421
|
+
|
|
422
|
+
# Combined with get_number_converter (correct order):
|
|
423
|
+
# "1.234,56 €" -> "1234.56 €" -> "1234.56"
|
|
424
|
+
col_def = ColDefinition(
|
|
425
|
+
file_col_name="Montant",
|
|
426
|
+
df_col_name="amount",
|
|
427
|
+
df_col_type=float,
|
|
428
|
+
df_col_convertor=[
|
|
429
|
+
Converters.get_number_converter(thousand_sep=".", decimal_sep=","),
|
|
430
|
+
Converters.get_sign_striping_conveter(),
|
|
431
|
+
],
|
|
432
|
+
)
|
|
433
|
+
"""
|
|
434
|
+
pattern = re.compile(r"[-+]?\d+(?:\.\d+)?")
|
|
435
|
+
|
|
436
|
+
def _convert(x: Any) -> Any:
|
|
437
|
+
# Handle missing values
|
|
438
|
+
if pd.isna(x) or x == "":
|
|
439
|
+
return x
|
|
440
|
+
|
|
441
|
+
s = str(x)
|
|
442
|
+
match = pattern.search(s)
|
|
443
|
+
return match.group(0) if match else s
|
|
444
|
+
|
|
445
|
+
return _convert
|
|
446
|
+
|
|
447
|
+
@classmethod
|
|
448
|
+
def chain_converters(
|
|
449
|
+
cls, converters: Sequence[Callable[[Any], Any]]
|
|
450
|
+
) -> Callable[[Any], Any]:
|
|
451
|
+
"""Chain multiple converter functions together.
|
|
452
|
+
|
|
453
|
+
Takes a sequence of converter functions and returns a single function
|
|
454
|
+
that applies them in order, passing the output of each function as
|
|
455
|
+
input to the next.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
converters: Sequence of converter callables to chain. Each callable
|
|
459
|
+
should accept a value and return a transformed value.
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
A single callable that applies all converters in sequence.
|
|
463
|
+
|
|
464
|
+
Example::
|
|
465
|
+
|
|
466
|
+
# Chain string stripper with uppercase converter
|
|
467
|
+
chained = Converters.chain_converters([
|
|
468
|
+
lambda x: None if x is None else str(x).strip(),
|
|
469
|
+
lambda x: x.upper() if x else x,
|
|
470
|
+
])
|
|
471
|
+
|
|
472
|
+
# Use in ColDefinition
|
|
473
|
+
col_def = ColDefinition(
|
|
474
|
+
file_col_name="Name",
|
|
475
|
+
df_col_name="name",
|
|
476
|
+
df_col_type=str,
|
|
477
|
+
df_col_convertor=chained,
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
# Or directly with a list
|
|
481
|
+
col_def = ColDefinition(
|
|
482
|
+
file_col_name="Name",
|
|
483
|
+
df_col_name="name",
|
|
484
|
+
df_col_type=str,
|
|
485
|
+
df_col_convertor=[
|
|
486
|
+
lambda x: None if x is None else str(x).strip(),
|
|
487
|
+
lambda x: x.upper() if x else x,
|
|
488
|
+
],
|
|
489
|
+
)
|
|
490
|
+
"""
|
|
491
|
+
if not converters:
|
|
492
|
+
raise ValueError("converters sequence cannot be empty")
|
|
493
|
+
|
|
494
|
+
if len(converters) == 1:
|
|
495
|
+
return converters[0]
|
|
496
|
+
|
|
497
|
+
def _chained(x: Any) -> Any:
|
|
498
|
+
result = x
|
|
499
|
+
for converter in converters:
|
|
500
|
+
result = converter(result)
|
|
501
|
+
return result
|
|
502
|
+
|
|
503
|
+
return _chained
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PandasHelpers:
|
|
10
|
+
"""A class grouping various pandas helper methods"""
|
|
11
|
+
|
|
12
|
+
@staticmethod
|
|
13
|
+
def round_value(df: pd.DataFrame, cols: Iterable[str]) -> pd.DataFrame:
|
|
14
|
+
"""Round the dataframe df columns listed in cols
|
|
15
|
+
Meant to be used inside a .pipe
|
|
16
|
+
Args:
|
|
17
|
+
df (pandas.DataFRame): the dataframe to process
|
|
18
|
+
cols (list[str]): The list of columns to treat
|
|
19
|
+
Return:
|
|
20
|
+
A dataframe with cols values rounded
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def converter(col: str) -> float:
|
|
24
|
+
"""The internal converter"""
|
|
25
|
+
return round(pd.to_numeric(col, errors="coerce"))
|
|
26
|
+
|
|
27
|
+
df = df.copy()
|
|
28
|
+
columns = list(cols)
|
|
29
|
+
df[columns] = df[columns].apply(converter)
|
|
30
|
+
return df
|