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.
@@ -0,0 +1,929 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import json
5
+ import logging
6
+ import os
7
+ from collections.abc import Mapping, Sequence
8
+ from pathlib import Path
9
+ from typing import Any, Callable, TextIO, Union, cast
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from .converters import Converters
15
+
16
+
17
+ @dataclasses.dataclass()
18
+ class ColDefinition:
19
+ """Definition of a column in the excel or csv file and in the dataframe.
20
+
21
+ file_col_name or file_col_number defines the column to read in the excel or csv file. One of them and only one must be defined.
22
+ if both file_col_name and file_col_number are defined an error is raised.
23
+
24
+ !CAUTION!: it is not possible to mix file_col_name and file_col_number for columns of the same input.
25
+
26
+ df_col_name defines the name of the column in the dataframe.
27
+ If file_col_name is defined then df_col_name can be missing and the column will be named with the value of file_col_name in the dataframe.
28
+ If file_col_number is defined then df_col_name must be defined.
29
+
30
+ If both file_col_name and df_col_name are defined the column will be named with the value of df_col_name in the dataframe.
31
+ If neither file_col_name nor df_col_name are defined an exception will be raised because we refuse to name dataframe columns with number !
32
+
33
+ If neiter of file_col_name and file_col_number are defined then df_col_name must be defined and a new column named with the value of df_col_name will
34
+ be created in the dataframe. The value of the column will be NAN. Use default to fill values in it.
35
+
36
+ To read a csv file:
37
+ - If the csv file has a header that you want to use you must set the "header" parameter of the read methods to the line number of the header (starting at 0).
38
+ In this case you can use only file_col_name to define the file columns (note that using file_col_number is also possible)
39
+ - If you don't want to use the header or the file has no header you must set "header" to None and use file_col_number. In this case file_col_name
40
+ must be ommited.
41
+
42
+ If default is defined all NA or NAN in the column will be replaced by the value of default.
43
+ df_col_type defines the type of the column in the dataframe. Can be a Python type (int, float, str, bool) or a pandas dtype string
44
+ (e.g., "Int64", "Float64", "boolean" for nullable types). Default is string.
45
+ df_col_bool_convertor_key defines a special convertor for boolean columns. The provided key defines the True value, other values defines False. The key in case
46
+ unsensitive, spaces are trimed and only the start of the string is checked (e.g. "yes" will match "Yes", "YES", "yes indeed", but not "no yes").
47
+ strip defines if the column values should be stripped of leading/trailing
48
+ whitespace before NA detection and any other conversion. This can
49
+ reveal an NA marker surrounded by whitespace. This parameter is
50
+ independent of strip_all in ColMapping.
51
+ na_values defines a list of additional strings to recognise as NA/NaN for this specific column,
52
+ merged with :attr:`ColMapping.na_values`. Pandas built-in defaults are still recognised unless
53
+ ``keep_default_na=False`` is set at the :class:`ColMapping` level. NA
54
+ detection is automatic and short-circuits the conversion chain.
55
+ df_col_convertor defines a custom convertor for the column. It will be used only if df_col_bool_convertor_key is not defined.
56
+ It can be either a single callable or a sequence of callables. If a sequence is provided, the converters will be chained
57
+ automatically, with each converter receiving the output of the previous
58
+ one. The complete order is strip, NA detection, then custom converters;
59
+ recognized NA values are never passed to these callables.
60
+
61
+ Example::
62
+
63
+ # Single converter
64
+ col_def = ColDefinition(
65
+ file_col_name="Amount",
66
+ df_col_name="amount",
67
+ df_col_type=float,
68
+ df_col_convertor=lambda x: float(x.replace(",", "."))
69
+ )
70
+
71
+ # Chained converters with strip
72
+ col_def = ColDefinition(
73
+ file_col_name="Name",
74
+ df_col_name="name",
75
+ df_col_type=str,
76
+ strip=True, # Automatically strip whitespace
77
+ df_col_convertor=[
78
+ lambda x: x.upper() if x else x, # Then: convert to uppercase
79
+ lambda x: x.replace("-", "_") if x else x, # Finally: replace dashes
80
+ ]
81
+ )
82
+ """
83
+
84
+ file_col_name: str | None = None
85
+ file_col_number: int | None = None
86
+ df_col_name: str | None = None
87
+ df_col_type: type | str = "string"
88
+ in_index: bool = False
89
+ df_col_default: Any | None = None
90
+ df_col_bool_convertor_key: str | None = None
91
+ strip: bool = False
92
+ na_values: list[str] | None = None
93
+ df_col_convertor: Callable[..., Any] | Sequence[Callable[..., Any]] | None = None
94
+
95
+ def __post_init__(self) -> None:
96
+ if self.file_col_name is not None and self.file_col_number is not None:
97
+ raise ValueError(
98
+ "Only one of file_col_name and file_col_number can be defined at the same time"
99
+ )
100
+ if (
101
+ self.file_col_name is None
102
+ and self.file_col_number is None
103
+ and self.df_col_name is None
104
+ ):
105
+ raise RuntimeError(
106
+ "df_col_name must be defined when neither file_col_name nor file_col_number is defined."
107
+ )
108
+
109
+ # Chain converters if a sequence is provided
110
+ if isinstance(self.df_col_convertor, Sequence) and not callable(
111
+ self.df_col_convertor
112
+ ):
113
+ # Cast to indicate to type checker that after chaining, it's always a Callable
114
+ self.df_col_convertor = cast(
115
+ Callable[..., Any], Converters.chain_converters(self.df_col_convertor)
116
+ )
117
+
118
+
119
+ @dataclasses.dataclass
120
+ class ColMapping:
121
+ """Column mapping specification used for both reading and writing DataFrames.
122
+
123
+ Controls which columns are selected and how they are renamed. Column
124
+ **order**, however, is handled differently between read and write — see
125
+ below. The semantics of :attr:`col_defs` also differ slightly between
126
+ the two kinds of operations:
127
+
128
+ - **Reading** (``read_csv``, ``read_excel_sheet``): ``file_col_name`` is
129
+ the column name **in the source file**; ``df_col_name`` becomes the
130
+ column name **in the resulting DataFrame**. All other
131
+ :class:`ColDefinition` fields (type, convertor, default, index…) are
132
+ fully applied. The resulting column **order always follows the
133
+ source file's original column order**, never the order of *col_defs*:
134
+ pandas ignores the order in which columns are requested (via
135
+ ``usecols``) and returns them in file order. Use *col_defs* order to
136
+ control renaming/typing, not positioning.
137
+ - **Writing** (``write_csv``, ``add_excel_sheet``): ``df_col_name`` is
138
+ the column name **in the DataFrame**; ``file_col_name`` becomes the column
139
+ header **in the output file**. All other :class:`ColDefinition` fields
140
+ are ignored. Here the output column **order does follow** *col_defs*:
141
+ declared columns are written first, in list order.
142
+
143
+ Attributes:
144
+ col_defs: Ordered list of :class:`ColDefinition` objects.
145
+ **When writing**, declared columns appear first in the output,
146
+ in list order, and columns not listed are handled according to
147
+ *include_all*.
148
+ **When reading**, this list order has no effect on the resulting
149
+ column order (which always matches the source file); it only
150
+ controls which source columns are selected, renamed, typed, and
151
+ converted. Columns not listed are handled according to
152
+ *include_all*.
153
+ exclusions: Column names that must **never** appear in the output,
154
+ regardless of *include_all* or *col_defs*. A column present in
155
+ both *col_defs* and *exclusions* is excluded with a warning.
156
+ include_all: When ``True`` (default), every column that is neither in
157
+ *col_defs* nor in *exclusions* is appended as-is after the
158
+ declared columns. When ``False``, only columns declared in
159
+ *col_defs* are kept. Forced to ``True`` when *col_defs* is empty.
160
+ strip_all: When ``True``, automatically strip leading/trailing whitespace
161
+ from all column values during reading. This applies to all columns,
162
+ even those not explicitly declared in *col_defs*. Individual columns
163
+ can enable this with their own ``strip`` parameter. Stripping runs
164
+ before NA detection, so it can reveal a marker surrounded by
165
+ whitespace. Defaults to ``False``.
166
+ na_values: Additional strings to treat as NA/NaN for **all** columns.
167
+ Applied to declared columns (merged with any per-column
168
+ :attr:`ColDefinition.na_values`) and to undeclared ``include_all``
169
+ columns. For converted columns, detection occurs before the first
170
+ boolean or custom converter and short-circuits that chain. Defaults
171
+ to ``None`` (no additional NA strings).
172
+ keep_default_na: Passed directly to ``pd.read_csv`` / ``pd.read_excel``.
173
+ When ``False``, suppress pandas' built-in NA strings for **all** columns.
174
+ Defaults to ``True``.
175
+ skiprows: Number of lines to skip at the start of the file before reading,
176
+ passed directly to ``pd.read_csv`` / ``pd.read_excel`` (same parameter
177
+ name as pandas). Useful to skip leading metadata rows that are not
178
+ part of the tabular data. Defaults to ``None`` (no rows skipped).
179
+
180
+ Example — **read**: rename a column, type it, and keep all others::
181
+
182
+ mapping = ColMapping(
183
+ col_defs=[
184
+ ColDefinition(file_col_name="Montant", df_col_name="amount", df_col_type=float),
185
+ ],
186
+ exclusions=["internal_id"],
187
+ )
188
+ df = DFFileMapper.read_csv(
189
+ "data.csv", cpl_mapping=CompiledMapping(mapping), header=0
190
+ )
191
+
192
+ Example — **read**: load only explicitly declared columns::
193
+
194
+ mapping = ColMapping(
195
+ col_defs=[
196
+ ColDefinition(file_col_name="Date", df_col_name="date"),
197
+ ColDefinition(file_col_name="Close", df_col_name="close", df_col_type=float),
198
+ ],
199
+ include_all=False,
200
+ )
201
+ df = DFFileMapper.read_csv(
202
+ "prices.csv", cpl_mapping=CompiledMapping(mapping), header=0
203
+ )
204
+
205
+ Example — **read/write**: exclude columns, no explicit col_defs needed::
206
+
207
+ mapping = ColMapping(exclusions=["Unnamed: 0", "internal_id"])
208
+ df = DFFileMapper.read_csv(
209
+ "export.csv", cpl_mapping=CompiledMapping(mapping), header=0
210
+ )
211
+ DFFileMapper.write_csv(df, "clean.csv", col_mapping=mapping)
212
+
213
+ Example — **write**: rename DataFrame columns in the output file::
214
+
215
+ mapping = ColMapping(
216
+ col_defs=[
217
+ ColDefinition(df_col_name="date", file_col_name="Date"),
218
+ ColDefinition(df_col_name="amount", file_col_name="Montant (€)"),
219
+ ],
220
+ exclusions=["internal_id"],
221
+ )
222
+ DFFileMapper.write_csv(df, "out.csv", col_mapping=mapping)
223
+
224
+ Example — **read**: strip whitespace from all columns::
225
+
226
+ mapping = ColMapping(
227
+ strip_all=True, # Strip all columns
228
+ exclusions=["internal_id"],
229
+ )
230
+ df = DFFileMapper.read_csv(
231
+ "data.csv", cpl_mapping=CompiledMapping(mapping), header=0
232
+ )
233
+
234
+ Example — **read**: strip only specific columns::
235
+
236
+ mapping = ColMapping(
237
+ col_defs=[
238
+ ColDefinition(file_col_name="Name", df_col_name="name", strip=True),
239
+ ColDefinition(file_col_name="Amount", df_col_name="amount", df_col_type=float),
240
+ ],
241
+ )
242
+ df = DFFileMapper.read_csv(
243
+ "data.csv", cpl_mapping=CompiledMapping(mapping), header=0
244
+ )
245
+
246
+ Example — **read**: skip leading metadata rows before the header::
247
+
248
+ mapping = ColMapping(
249
+ skiprows=3, # skip the first 3 lines of the file
250
+ exclusions=["internal_id"],
251
+ )
252
+ df = DFFileMapper.read_csv(
253
+ "report.csv", cpl_mapping=CompiledMapping(mapping), header=0
254
+ )
255
+ """
256
+
257
+ col_defs: list[ColDefinition] = dataclasses.field(default_factory=list)
258
+ exclusions: list[str] = dataclasses.field(default_factory=list)
259
+ include_all: bool = True
260
+ strip_all: bool = False
261
+ na_values: list[str] | None = None
262
+ keep_default_na: bool = True
263
+ skiprows: int | None = None
264
+
265
+ def __post_init__(self) -> None:
266
+ if not self.col_defs:
267
+ self.include_all = True
268
+
269
+
270
+ @dataclasses.dataclass
271
+ class CompiledMapping:
272
+ """Compiled read plan derived from a :class:`ColMapping`.
273
+
274
+ A :class:`ColMapping` is purely declarative (the *what*); this class is its
275
+ compiled form for the pandas read pipeline (the *how*). It translates the
276
+ declared :class:`ColDefinition` entries into the maps and lists consumed by
277
+ :class:`DFFileMapper` read methods (converters, dtype casts, renames,
278
+ ``usecols``, per-column ``na_values``…).
279
+
280
+ The compilation runs once, eagerly, at construction. Building a single
281
+ :class:`CompiledMapping` and reusing it across calls — e.g. reading its
282
+ :attr:`headers` then passing it to :meth:`DFFileMapper.read_csv` — therefore
283
+ performs the compilation only once. The instance is meant to be treated as
284
+ immutable; the source *col_mapping* must not be mutated afterwards.
285
+
286
+ Attributes:
287
+ col_mapping: The declarative source mapping this plan was compiled from.
288
+ columns_list: Source columns (names or indices) to read.
289
+ column_renamer_map: Source column -> DataFrame column renames.
290
+ convertor_map: Source column -> per-value pandas converter.
291
+ assign_map: Synthetic DataFrame column -> fill value (``np.nan``).
292
+ type_map: DataFrame column -> declared dtype for the read-time cast.
293
+ filler_map: DataFrame column -> default value used to fill NA.
294
+ index_list: DataFrame columns to promote to the index.
295
+ na_values_map: Source column -> extra NA strings (mapping + per-column).
296
+ header_map: Ordered resulting-column -> declared dtype (index excluded).
297
+ include_all: Whether undeclared source columns are kept.
298
+ usecols: Columns to restrict the read to, or ``None`` to read every one.
299
+ """
300
+
301
+ _logger = logging.getLogger(__name__)
302
+
303
+ col_mapping: ColMapping
304
+ columns_list: list[str | int] = dataclasses.field(init=False, default_factory=list)
305
+ column_renamer_map: dict[str | int, str] = dataclasses.field(
306
+ init=False, default_factory=dict
307
+ )
308
+ convertor_map: dict[str | int, Callable[[Any], bool | str | None]] = (
309
+ dataclasses.field(init=False, default_factory=dict)
310
+ )
311
+ assign_map: dict[str, Any] = dataclasses.field(init=False, default_factory=dict)
312
+ type_map: dict[str, str | type] = dataclasses.field(init=False, default_factory=dict)
313
+ filler_map: dict[str, str] = dataclasses.field(init=False, default_factory=dict)
314
+ index_list: list[str | int] = dataclasses.field(init=False, default_factory=list)
315
+ na_values_map: dict[str | int, list[str]] = dataclasses.field(
316
+ init=False, default_factory=dict
317
+ )
318
+ header_map: dict[str, str | type] = dataclasses.field(
319
+ init=False, default_factory=dict
320
+ )
321
+ include_all: bool = dataclasses.field(init=False, default=True)
322
+ usecols: list[str | int] | None = dataclasses.field(init=False, default=None)
323
+
324
+ def __post_init__(self) -> None:
325
+ self._compile()
326
+
327
+ @property
328
+ def headers(self) -> dict[str, str | type]:
329
+ """Return the declared resulting-column -> dtype mapping (no I/O).
330
+
331
+ Only columns declared in :attr:`ColMapping.col_defs` appear; columns
332
+ picked up from a file via :attr:`ColMapping.include_all` cannot, since
333
+ no source is read. Each dtype is the declared read-time resolution
334
+ (``"boolean"`` for a bool convertor key, ``"string"`` for the Python
335
+ ``str`` type, otherwise the declared value). Columns flagged
336
+ :attr:`ColDefinition.in_index` are excluded since they become the index.
337
+ """
338
+ return dict(self.header_map)
339
+
340
+ def _compile(self) -> None:
341
+ """Populate the compiled maps and lists from :attr:`col_mapping`.
342
+
343
+ Column definitions whose source column is also listed in
344
+ :attr:`ColMapping.exclusions` are skipped (with a warning) so the
345
+ exclusion always wins over an explicit definition.
346
+ """
347
+ col_mapping = self.col_mapping
348
+ exclusions: set[str] = set(col_mapping.exclusions)
349
+
350
+ # Warn and skip col_defs whose source column is also in exclusions
351
+ effective_col_defs: list[ColDefinition] = []
352
+ for cd in col_mapping.col_defs:
353
+ if cd.file_col_name is not None and cd.file_col_name in exclusions:
354
+ self._logger.warning(
355
+ f"Column '{cd.file_col_name}' is in both col_defs and exclusions — it will be excluded."
356
+ )
357
+ else:
358
+ effective_col_defs.append(cd)
359
+
360
+ self.include_all = col_mapping.include_all
361
+
362
+ for col_def in effective_col_defs:
363
+
364
+ # compute the df name of the column
365
+ if col_def.df_col_name is not None:
366
+ df_name = col_def.df_col_name
367
+ elif col_def.file_col_name is not None:
368
+ # if there is no df_name with use the same name as the source if there is one.
369
+ df_name = col_def.file_col_name
370
+ else:
371
+ # we need at least the name of the column in the source or a name to put on the df column. We refuse to use the number of the column as df name !
372
+ raise RuntimeError("One of file_col_name or df_name must be defined")
373
+
374
+ # Resolve the declared dtype using the same rule as the read-time astype:
375
+ # a bool convertor forces "boolean", the Python str type maps to the pandas
376
+ # StringDtype "string", any other value passes through unchanged.
377
+ if col_def.df_col_bool_convertor_key is not None:
378
+ header_dtype: str | type = "boolean"
379
+ else:
380
+ header_dtype = (
381
+ "string" if col_def.df_col_type is str else col_def.df_col_type
382
+ )
383
+
384
+ # compute the name or index of the column in the source file and look if we need to rename it
385
+ col_name: Union[str, int, None] = None
386
+ if col_def.file_col_number is not None and col_def.file_col_name is not None:
387
+ raise ValueError(
388
+ "Only one of file_col_name and file_col_number can be defined at the same time"
389
+ )
390
+ elif col_def.file_col_name is not None:
391
+ self._logger.debug(
392
+ f"Using file_col_name for column {col_def.file_col_name}"
393
+ )
394
+ col_name = col_def.file_col_name
395
+ if col_name != df_name:
396
+ self.column_renamer_map[col_name] = df_name
397
+ elif col_def.file_col_number is not None:
398
+ self._logger.debug(
399
+ f"No file_col_name, using file_col_number for column {col_def.file_col_number}"
400
+ )
401
+ col_name = col_def.file_col_number
402
+ self.column_renamer_map[col_name] = df_name
403
+ else:
404
+ col_name = None
405
+
406
+ if col_name is None:
407
+ # its a new column.
408
+ self.assign_map[df_name] = np.nan
409
+
410
+ else:
411
+ # add this column to the column that are to be read from the source file.
412
+ self.columns_list.append(col_name)
413
+
414
+ # Determine if we need to apply strip
415
+ should_strip = col_mapping.strip_all or col_def.strip
416
+
417
+ # Merge mapping-level and per-column na_values into the dict
418
+ # passed to pandas via na_values. pandas applies this dict in
419
+ # combination with keep_default_na as documented. Computed
420
+ # early so it can also be used below to make custom
421
+ # converters NA-aware.
422
+ _mapping_na: list[str] = list(col_mapping.na_values or [])
423
+ _col_na: list[str] = list(col_def.na_values or [])
424
+ _effective_na: list[str] = _mapping_na + _col_na
425
+ if _effective_na:
426
+ self.na_values_map[col_name] = _effective_na
427
+
428
+ converters: list[Callable[[Any], Any]] = []
429
+
430
+ # add bool converter if necessary, if no bool converter we can add a custom converter if there is one defined
431
+ if col_def.df_col_bool_convertor_key is not None:
432
+ converters.append(
433
+ Converters.get_bool_convertor(col_def.df_col_bool_convertor_key)
434
+ )
435
+ elif col_def.df_col_convertor is not None:
436
+ # After __post_init__, df_col_convertor is always a Callable (chained if necessary)
437
+ converters.append(
438
+ cast(Callable[[Any], Any], col_def.df_col_convertor)
439
+ )
440
+
441
+ if should_strip or converters:
442
+ converter = (
443
+ Converters.chain_converters(converters) if converters else None
444
+ )
445
+
446
+ def _convert(
447
+ value: Any,
448
+ *,
449
+ _converter: Callable[[Any], Any] | None = converter,
450
+ _should_strip: bool = should_strip,
451
+ _na_values: tuple[str, ...] = tuple(_effective_na),
452
+ _keep_default_na: bool = col_mapping.keep_default_na,
453
+ ) -> Any:
454
+ if _should_strip and value is not None:
455
+ value = str(value).strip()
456
+ normalized = Converters._na_safe(
457
+ value,
458
+ na_values=_na_values,
459
+ keep_default_na=_keep_default_na,
460
+ )
461
+ if isinstance(normalized, float) and pd.isna(normalized):
462
+ return normalized
463
+ return (
464
+ _converter(normalized)
465
+ if _converter is not None
466
+ else normalized
467
+ )
468
+
469
+ self.convertor_map[col_name] = _convert
470
+
471
+ # adding a type converter for this column
472
+ # Use pandas StringDtype ("string") for str columns so that NaN is
473
+ # preserved as pd.NA after the cast instead of being silently
474
+ # converted to the string "nan" by plain str / object dtype.
475
+ self.type_map[df_name] = header_dtype
476
+
477
+ if col_def.df_col_default is not None:
478
+ self.filler_map[df_name] = col_def.df_col_default
479
+
480
+ if col_def.in_index:
481
+ self.index_list.append(df_name)
482
+ else:
483
+ # Index columns become the DataFrame index, not columns, so they are
484
+ # excluded from the resulting-column header map.
485
+ self.header_map[df_name] = header_dtype
486
+
487
+ # test that all source definitions are of the same type either all str or all int.
488
+ # str if file_col_name is used, int if file_col_number is used.
489
+ if len(self.columns_list) > 1:
490
+ if not all(
491
+ type(self.columns_list[0]) == type(e) for e in self.columns_list[1:]
492
+ ):
493
+ raise AttributeError(
494
+ "All element of a ColDefinition Array must use the same source definition: either file_col_name, either file_col_number"
495
+ )
496
+
497
+ # Restrict reading to declared columns only when include_all is disabled
498
+ # and at least one source column is declared.
499
+ if not col_mapping.include_all and len(self.columns_list) > 0:
500
+ self.usecols = self.columns_list
501
+
502
+
503
+ class DFFileMapper:
504
+ """Read and write pandas DataFrames using CSV files.
505
+
506
+ All public methods are class methods so no instantiation is required.
507
+ Column selection, renaming, type conversion, and index configuration are
508
+ driven by a :class:`ColMapping` instance, which combines explicit
509
+ :class:`ColDefinition` entries with optional pass-through of all remaining
510
+ columns and an exclusion list.
511
+
512
+ Example — read only declared columns::
513
+
514
+ mapping = ColMapping(
515
+ col_defs=[
516
+ ColDefinition(file_col_name="Date", df_col_name="date", df_col_type=str),
517
+ ColDefinition(file_col_name="Close", df_col_name="close", df_col_type=float),
518
+ ],
519
+ include_all=False,
520
+ )
521
+ df = DFFileMapper.read_csv(
522
+ "prices.csv", cpl_mapping=CompiledMapping(mapping), header=0
523
+ )
524
+
525
+ Example — read all columns but exclude one::
526
+
527
+ mapping = ColMapping(exclusions=["Unnamed: 0"])
528
+ df = DFFileMapper.read_csv(
529
+ "export.csv", cpl_mapping=CompiledMapping(mapping), header=0
530
+ )
531
+ """
532
+
533
+ _logger = logging.getLogger(__name__)
534
+
535
+ @classmethod
536
+ def get_headers(
537
+ cls,
538
+ input: Any,
539
+ *,
540
+ cpl_mapping: CompiledMapping,
541
+ reader: Callable = pd.read_csv,
542
+ read_args: Mapping[str, Any] = {},
543
+ sample_rows: int | None = None,
544
+ ) -> dict[str, Any]:
545
+ """Return the effective resulting columns as a ``name -> dtype`` mapping.
546
+
547
+ The source *input* is actually read (optionally limited to *sample_rows*
548
+ rows) through the same pipeline as :meth:`read_to_df`, and the concrete
549
+ resulting dtypes are returned, including undeclared ``include_all``
550
+ columns.
551
+
552
+ For the declared schema without any I/O, use
553
+ :attr:`CompiledMapping.headers` instead.
554
+
555
+ Args:
556
+ input: Data source accepted by *reader* (path, URL, or file-like
557
+ object).
558
+ cpl_mapping: The :class:`CompiledMapping` describing the read plan.
559
+ reader: The pandas read callable. Defaults to
560
+ :func:`pandas.read_csv`; pass :func:`pandas.read_excel` for
561
+ Excel sources.
562
+ read_args: Extra keyword arguments forwarded to *reader*.
563
+ sample_rows: When set, limit the read to this many rows (via
564
+ ``nrows``) to speed up dtype inference. Defaults to ``None``
565
+ (read the whole source).
566
+
567
+ Returns:
568
+ An ordered mapping from resulting column name to its concrete pandas
569
+ dtype.
570
+ """
571
+ effective_read_args: dict[str, Any] = dict(read_args)
572
+ if sample_rows is not None:
573
+ effective_read_args["nrows"] = sample_rows
574
+ res_df = cls.read_to_df(
575
+ reader,
576
+ input=input,
577
+ cpl_mapping=cpl_mapping,
578
+ read_args=effective_read_args,
579
+ )
580
+ return {str(col): res_df[col].dtype for col in res_df.columns}
581
+
582
+ @classmethod
583
+ def read_to_df(
584
+ cls,
585
+ reader: Callable,
586
+ *,
587
+ input: Any,
588
+ cpl_mapping: CompiledMapping,
589
+ read_args: Mapping[str, Any] = {},
590
+ ) -> pd.DataFrame:
591
+ """Generic low-level reader used by tabular file adapters.
592
+
593
+ Uses the pre-compiled *cpl_mapping* plan, delegates the actual I/O to
594
+ *reader* (a ``pandas`` read function such as ``pd.read_csv``), then
595
+ renames columns, creates synthetic columns, fills defaults, converts
596
+ types, and optionally sets the DataFrame index.
597
+
598
+ When :attr:`ColMapping.include_all` is ``True`` the reader is invoked
599
+ without ``usecols`` so that all source columns are present; after
600
+ transformation, columns listed in :attr:`ColMapping.exclusions` are
601
+ dropped. When ``include_all`` is ``False`` only the columns declared
602
+ in :attr:`ColMapping.col_defs` are requested via ``usecols``.
603
+
604
+ Args:
605
+ reader: A pandas read callable (e.g. ``pd.read_csv``,
606
+ ``pd.read_excel``).
607
+ input: The data source accepted by *reader* — a file path, URL,
608
+ or file-like object.
609
+ cpl_mapping: A :class:`CompiledMapping` describing which columns to
610
+ read and how to transform them.
611
+ read_args: Extra keyword arguments forwarded directly to *reader*.
612
+
613
+ Returns:
614
+ A :class:`~pandas.DataFrame` shaped and typed according to the
615
+ compiled plan.
616
+ """
617
+ col_mapping = cpl_mapping.col_mapping
618
+ exclusions: set[str] = set(col_mapping.exclusions)
619
+
620
+ include_all: bool = cpl_mapping.include_all
621
+ pars: dict[str, Any] = {"converters": cpl_mapping.convertor_map}
622
+
623
+ # Build the per-column na_values dict from declared col_defs.
624
+ pars["na_values"] = dict(cpl_mapping.na_values_map)
625
+ pars["keep_default_na"] = col_mapping.keep_default_na
626
+
627
+ if col_mapping.skiprows is not None:
628
+ pars["skiprows"] = col_mapping.skiprows
629
+
630
+ if cpl_mapping.usecols is not None:
631
+ # Restrict reading to only the declared columns
632
+ pars["usecols"] = cpl_mapping.usecols
633
+ # else: read all columns; converters still apply only to col_defs cols
634
+
635
+ cls._logger.info(f"Reading with parameters: {pars} and read_args: {read_args}")
636
+ res_df: pd.DataFrame = reader(input, **pars, **read_args)
637
+
638
+ # Propagate col_mapping-level na_values to undeclared columns (include_all mode).
639
+ # Per-column na_values (from col_defs) are already handled by pandas via the
640
+ # na_values dict above; undeclared columns receive no entry in that dict so we
641
+ # apply the replacement manually after reading.
642
+ if include_all and col_mapping.na_values:
643
+ _mapping_na_list = list(col_mapping.na_values)
644
+ _declared = set(cpl_mapping.columns_list)
645
+ for _col in res_df.columns:
646
+ if _col not in _declared:
647
+ res_df[_col] = res_df[_col].replace(_mapping_na_list, np.nan)
648
+
649
+ res_df = (
650
+ res_df.rename(columns=cpl_mapping.column_renamer_map)
651
+ .assign(**cpl_mapping.assign_map)
652
+ .fillna(cpl_mapping.filler_map)
653
+ .astype(cpl_mapping.type_map)
654
+ )
655
+
656
+ # Cast undeclared include_all columns that pandas read as object dtype to
657
+ # StringDtype so they behave like declared str columns (NA preserved as
658
+ # pd.NA instead of np.nan, no "nan" string leakage).
659
+ if include_all:
660
+ _declared_df_names = set(cpl_mapping.type_map.keys())
661
+ _undeclared_str: dict[str, str] = {
662
+ col: "string"
663
+ for col in res_df.columns
664
+ if col not in _declared_df_names and res_df[col].dtype == object
665
+ }
666
+ if _undeclared_str:
667
+ res_df = res_df.astype(_undeclared_str)
668
+
669
+ if cpl_mapping.index_list:
670
+ res_df = res_df.set_index(cpl_mapping.index_list)
671
+
672
+ if include_all and exclusions:
673
+ cols_to_drop = [c for c in exclusions if c in res_df.columns]
674
+ if cols_to_drop:
675
+ res_df = res_df.drop(columns=cols_to_drop)
676
+
677
+ return res_df
678
+
679
+ @classmethod
680
+ def read_csv(
681
+ cls,
682
+ input: Union[str, TextIO, os.PathLike],
683
+ *,
684
+ cpl_mapping: CompiledMapping,
685
+ sep: str | None = None,
686
+ header: int | None = 0,
687
+ decimal: str | None = None,
688
+ thousands: str | None = None,
689
+ read_csv_args: Mapping[str, Any] | None = None,
690
+ ) -> pd.DataFrame:
691
+ """Read a CSV file into a DataFrame according to the compiled mapping provided.
692
+
693
+ The engine is always forced to ``"python"`` to ensure consistent
694
+ behaviour across separator types. If *header*, *sep*, *decimal*, or
695
+ *thousands* appear in both *read_csv_args* and as explicit arguments,
696
+ the explicit argument takes precedence and a warning is logged.
697
+
698
+ Args:
699
+ input: Path, URL, or file-like object accepted by
700
+ :func:`pandas.read_csv`.
701
+ cpl_mapping: A :class:`CompiledMapping` that declares which columns to
702
+ read, how to transform them, and which to exclude. When
703
+ :attr:`ColMapping.include_all` is ``True`` (default), all source
704
+ columns not listed in :attr:`ColMapping.exclusions` are
705
+ included.
706
+ sep: Field delimiter for the CSV file. Defaults to ``","`` when
707
+ not specified here or in *read_csv_args*.
708
+ header: Row number (0-based) of the header line. Defaults to ``0``
709
+ (first line contains column names). Pass ``None``
710
+ when the file has no header, in which case *file_col_number*
711
+ must be used in the :class:`ColDefinition` entries.
712
+ decimal: Character recognized as decimal point. Defaults to
713
+ pandas default (``"."``). For European format use ``","``.
714
+ thousands: Character used as thousands separator. Defaults to
715
+ pandas default (``None``). For European format use ``" "``
716
+ or ``"."``.
717
+ read_csv_args: Additional keyword arguments forwarded to
718
+ :func:`pandas.read_csv`. Keys ``"header"``, ``"sep"``,
719
+ ``"decimal"``, ``"thousands"``, and ``"engine"`` are managed
720
+ by this method; providing ``"engine"`` with a value other
721
+ than ``"python"`` raises :exc:`RuntimeError`.
722
+
723
+ Returns:
724
+ A :class:`~pandas.DataFrame` shaped and typed according to
725
+ *col_mapping*.
726
+
727
+ Raises:
728
+ RuntimeError: If ``"engine"`` in *read_csv_args* is not
729
+ ``"python"``.
730
+ """
731
+ # Expand user home directory if present in path (but not for file handles)
732
+ if isinstance(input, (str, os.PathLike)):
733
+ input = Path(input).expanduser()
734
+
735
+ # we don't want to modify the read_csv_args provided by the user
736
+ csv_read_args: dict[str, Any] = dict(read_csv_args) if read_csv_args else {}
737
+
738
+ if "header" in csv_read_args and header is not None:
739
+ cls._logger.warning(
740
+ "header provided both in read_csv_args and as argument. The one provided as argument will be used."
741
+ )
742
+ csv_read_args = {k: v for k, v in csv_read_args.items() if k != "header"}
743
+
744
+ if "header" not in csv_read_args:
745
+ csv_read_args["header"] = header
746
+
747
+ if "sep" in csv_read_args and sep is not None:
748
+ cls._logger.warning(
749
+ "sep provided both in read_csv_args and as argument. The one provided as argument will be used."
750
+ )
751
+ csv_read_args = {k: v for k, v in csv_read_args.items() if k != "sep"}
752
+ if "sep" not in csv_read_args:
753
+ csv_read_args["sep"] = sep if sep is not None else ","
754
+
755
+ if "decimal" in csv_read_args and decimal is not None:
756
+ cls._logger.warning(
757
+ "decimal provided both in read_csv_args and as argument. The one provided as argument will be used."
758
+ )
759
+ csv_read_args = {k: v for k, v in csv_read_args.items() if k != "decimal"}
760
+ if "decimal" not in csv_read_args and decimal is not None:
761
+ csv_read_args["decimal"] = decimal
762
+
763
+ if "thousands" in csv_read_args and thousands is not None:
764
+ cls._logger.warning(
765
+ "thousands provided both in read_csv_args and as argument. The one provided as argument will be used."
766
+ )
767
+ csv_read_args = {k: v for k, v in csv_read_args.items() if k != "thousands"}
768
+ if "thousands" not in csv_read_args and thousands is not None:
769
+ csv_read_args["thousands"] = thousands
770
+
771
+ if "engine" in csv_read_args and csv_read_args["engine"] != "python":
772
+ raise RuntimeError("engine must be 'python'")
773
+
774
+ csv_read_args["engine"] = "python"
775
+
776
+ cls._logger.debug(
777
+ f"csv_read_args = {json.dumps(csv_read_args, indent=2, default=str)}"
778
+ )
779
+ res_df = cls.read_to_df(
780
+ pd.read_csv, input=input, cpl_mapping=cpl_mapping, read_args=csv_read_args
781
+ )
782
+ return res_df
783
+
784
+ @classmethod
785
+ def _apply_col_mapping_for_write(
786
+ cls,
787
+ df: pd.DataFrame,
788
+ col_mapping: ColMapping | None,
789
+ ) -> pd.DataFrame:
790
+ """Apply a :class:`ColMapping` to a DataFrame before writing it to a file.
791
+
792
+ Only the write-relevant fields of each :class:`ColDefinition` are used:
793
+
794
+ - ``df_col_name``: the column name **in the DataFrame** to select.
795
+ - ``file_col_name``: the column name to use **in the output file**
796
+ (rename target). When equal to *df_col_name* no rename occurs.
797
+
798
+ All other :class:`ColDefinition` fields (type, convertor, default,
799
+ index …) are ignored.
800
+
801
+ Columns listed in :attr:`~ColMapping.col_defs` are written first (in
802
+ list order). When :attr:`~ColMapping.include_all` is ``True``
803
+ (default), columns not mentioned but also not in
804
+ :attr:`~ColMapping.exclusions` are appended in their original order.
805
+ Columns in *exclusions* are always dropped.
806
+
807
+ Args:
808
+ df: Source :class:`~pandas.DataFrame`.
809
+ col_mapping: A :class:`ColMapping` instance, or ``None`` to write
810
+ all columns as-is.
811
+
812
+ Returns:
813
+ A new :class:`~pandas.DataFrame` with columns selected, renamed,
814
+ and ordered according to *col_mapping*.
815
+ """
816
+ if col_mapping is None:
817
+ return df
818
+
819
+ exclusions: set[str] = set(col_mapping.exclusions)
820
+ # Build (df_col, output_col) pairs from col_defs, skipping excluded ones
821
+ selected: list[tuple[str, str]] = []
822
+ for cd in col_mapping.col_defs:
823
+ src = cd.df_col_name
824
+ if src is None:
825
+ continue
826
+ if src in exclusions:
827
+ cls._logger.warning(
828
+ f"Column '{src}' is in both col_defs and exclusions — it will be excluded."
829
+ )
830
+ continue
831
+ dst = cd.file_col_name if cd.file_col_name is not None else src
832
+ selected.append((src, dst))
833
+
834
+ mentioned = {src for src, _ in selected}
835
+ ordered_cols = [src for src, _ in selected]
836
+
837
+ if col_mapping.include_all:
838
+ remaining = [
839
+ col
840
+ for col in df.columns
841
+ if col not in mentioned and col not in exclusions
842
+ ]
843
+ ordered_cols += remaining
844
+
845
+ rename_map = {src: dst for src, dst in selected if src != dst}
846
+ result = df[ordered_cols]
847
+ if rename_map:
848
+ result = result.rename(columns=rename_map)
849
+ return result
850
+
851
+ @classmethod
852
+ def write_csv(
853
+ cls,
854
+ df: pd.DataFrame,
855
+ output: Union[str, os.PathLike],
856
+ *,
857
+ sep: str = ",",
858
+ index: bool = False,
859
+ header: bool = True,
860
+ encoding: str = "utf-8",
861
+ col_mapping: ColMapping | None = None,
862
+ write_csv_args: Mapping[str, Any] | None = None,
863
+ ) -> None:
864
+ """Write a DataFrame to a CSV file.
865
+
866
+ Args:
867
+ df: The :class:`~pandas.DataFrame` to write.
868
+ output: Destination file path. ``~`` is expanded to the user's
869
+ home directory.
870
+ sep: Field delimiter to use. Defaults to ``","`` .
871
+ index: Whether to write the DataFrame index as a column.
872
+ Defaults to ``False``.
873
+ header: Whether to write the column names as the first line.
874
+ Defaults to ``True``.
875
+ encoding: File encoding. Defaults to ``"utf-8"``.
876
+ col_mapping: A :class:`ColMapping` instance controlling column
877
+ selection, renaming, and ordering for the written CSV.
878
+ :attr:`~ColMapping.col_defs` entries are used only for their
879
+ ``df_col_name`` (DataFrame column) and ``file_col_name``
880
+ (output header name); all other fields are ignored.
881
+ :attr:`~ColMapping.exclusions` columns are dropped.
882
+ When :attr:`~ColMapping.include_all` is ``True`` (default),
883
+ columns not mentioned are appended after the listed ones.
884
+ Defaults to ``None`` (all columns written as-is).
885
+
886
+ Example — rename ``"Amount"`` and drop ``"internal_id"``::
887
+
888
+ DFFileMapper.write_csv(
889
+ df,
890
+ "out.csv",
891
+ col_mapping=ColMapping(
892
+ col_defs=[
893
+ ColDefinition(df_col_name="date", file_col_name="Date"),
894
+ ColDefinition(df_col_name="Amount", file_col_name="Montant (€)"),
895
+ ],
896
+ exclusions=["internal_id"],
897
+ ),
898
+ )
899
+
900
+ write_csv_args: Additional keyword arguments forwarded to
901
+ :meth:`~pandas.DataFrame.to_csv`. Keys ``"sep"``,
902
+ ``"index"``, ``"header"``, and ``"encoding"`` are managed by
903
+ this method; providing them in *write_csv_args* raises a
904
+ warning and the explicit argument values take precedence.
905
+
906
+ Raises:
907
+ OSError: If the destination path cannot be written to.
908
+ """
909
+ output = Path(output).expanduser()
910
+ df = cls._apply_col_mapping_for_write(df, col_mapping)
911
+
912
+ csv_write_args: dict[str, Any] = dict(write_csv_args) if write_csv_args else {}
913
+
914
+ for key, value in [
915
+ ("sep", sep),
916
+ ("index", index),
917
+ ("header", header),
918
+ ("encoding", encoding),
919
+ ]:
920
+ if key in csv_write_args:
921
+ cls._logger.warning(
922
+ f"'{key}' provided both in write_csv_args and as argument. "
923
+ "The explicit argument value will be used."
924
+ )
925
+ csv_write_args.pop(key)
926
+ csv_write_args[key] = value
927
+
928
+ cls._logger.debug(f"Writing CSV to {output} with args: {csv_write_args}")
929
+ df.to_csv(output, **csv_write_args)