Normalizer (kadi.kidas.normalizer)¶
Normalizer is the agricultural data normalization class of KadiPy, tailored for the Beninese context. It gathers six transformations: column name normalization to snake_case, unit conversion to kilograms, currency conversion, crop name standardization to FAO codes, market geocoding, and creation of Shapely GPS geometries.
Each method updates the internal DataFrame and returns it, allowing method chaining in a single expression. The history of applied transformations is accessible via mappings().
Initialization¶
Normalizer receives a pandas.DataFrame and creates an internal copy. The original DataFrame is never modified.
Exception: CleanError if the provided argument is not a DataFrame.
Normalization Methods¶
norm_cols(style='snake_case')¶
Normalizes DataFrame column names to snake_case: accent removal, replacing spaces, hyphens, and parentheses with underscores, converting to lowercase.
# Before: ['Culture', 'Rendement (kg)', 'Température Min (°C)', 'Date Récolte']
df_norm = normalizer.norm_cols()
# After: ['culture', 'rendement_kg', 'temperature_min_c', 'date_recolte']
| Parameter | Type | Default | Description |
|---|---|---|---|
style |
str |
'snake_case' |
Target style. Only 'snake_case' is currently supported. |
A style other than 'snake_case' emits a log warning and the operation is still applied in snake_case.
Returns: pd.DataFrame
convert_units(unit_map)¶
Converts numeric values of specified columns to kilograms, applying conversion factors from the internal reference table.
df_norm = normalizer.convert_units({
"production": "tonne",
"recolte": "sac_100kg",
"stock_local": "tiya",
})
| Parameter | Type | Description |
|---|---|---|
unit_map |
dict[str, str] |
Dictionary column_name -> source_unit |
Supported Units:
| Unit | Factor to kg |
|---|---|
'kg', 'kilogramme' |
1.0 |
'tonne', 'tonnes', 't' |
1000.0 |
'sac_100kg', 'sac' |
100.0 |
'sac_80kg' |
80.0 |
'sac_50kg' |
50.0 |
'tiya' |
1.5 |
'quintal' |
100.0 |
'boisseau' |
27.2 |
'livre' |
0.4536 |
'g', 'gramme' |
0.001 |
The standard 'sac' corresponds to the 100 kg bag used in Benin. The 'tiya' is a local measure of approximately 1.5 kg depending on the crop. A column missing from the DataFrame emits a log warning and is ignored without raising an error.
Returns: pd.DataFrame
Exception: CleanError if a source unit is unknown.
convert_currency(col, from_='XOF', to='XOF', date=None)¶
Converts monetary values of a column using a fixed exchange rate.
# Conversion from USD to XOF
df_norm = normalizer.convert_currency(
col="prix_usd",
from_="USD",
to="XOF",
)
# Conversion from EUR to XOF
df_norm = normalizer.convert_currency(
col="valeur_export",
from_="EUR",
to="XOF",
)
| Parameter | Type | Default | Description |
|---|---|---|---|
col |
str |
required | Name of the column to convert |
from_ |
str |
'XOF' |
Source currency |
to |
str |
'XOF' |
Target currency |
date |
str or None |
None |
Reference date in 'YYYY-MM-DD' format (unused in current version) |
Available Exchange Rates (fixed, to XOF):
| Currency | Rate to XOF |
|---|---|
'XOF' |
1.0 |
'EUR' |
655.957 (WAEMU fixed rate) |
'USD' |
600.0 |
'GBP' |
750.0 |
If one of the currencies is not in this table, a warning is emitted and no conversion is applied.
The current version uses fixed rates. Integration with a real-time exchange rate API is planned for phase 2 of the module.
Returns: pd.DataFrame
std_crops(col, std='fao')¶
Normalizes crop names in a column to official FAO codes, handling local Beninese variants with or without accents.
# Before: ['maïs', 'Niébé', 'MANIOC', 'yam', 'mais']
df_norm = normalizer.std_crops(col="culture")
# After: ['maize', 'cowpea', 'cassava', 'yam', 'maize']
| Parameter | Type | Default | Description |
|---|---|---|---|
col |
str |
required | Name of the column containing crop names |
std |
str |
'fao' |
Target standard ('fao' uses official FAO codes) |
Available Mappings:
| Accepted Local Names | FAO Code |
|---|---|
'maïs', 'mais', 'maiz', 'corn', 'maize' |
'maize' |
'niébé', 'niebe', 'cowpea', 'haricot' |
'cowpea' |
'igname', 'yam' |
'yam' |
'sorgho', 'sorghum' |
'sorghum' |
'riz', 'rice' |
'rice' |
'manioc', 'cassava' |
'cassava' |
'arachide', 'groundnut', 'peanut' |
'groundnut' |
'mil', 'millet' |
'millet' |
'fonio' |
'fonio' |
'soja', 'soybean' |
'soybean' |
'tomate', 'tomato' |
'tomato' |
'oignon', 'onion' |
'onion' |
'piment', 'pepper' |
'pepper' |
Unrecognized names are kept in lowercase without accents. A missing column emits a warning and is ignored.
Returns: pd.DataFrame
std_markets(col, region='benin')¶
Normalizes market names in a column and adds two columns market_lat and market_lon with official GPS coordinates.
# Before: ['Dantokpa', 'PARAKOU', 'Bohicon']
df_norm = normalizer.std_markets(col="marche")
# After: 'marche' column unchanged, + 'market_lat' and 'market_lon' columns
| Parameter | Type | Default | Description |
|---|---|---|---|
col |
str |
required | Name of the column containing market names |
region |
str |
'benin' |
Reference region for market dictionary |
Referenced Markets (Benin):
| Market | Latitude | Longitude | City |
|---|---|---|---|
dantokpa, cotonou |
6.366 | 2.437 | Cotonou |
parakou |
9.337 | 2.629 | Parakou |
bohicon |
7.181 | 2.067 | Bohicon |
kandi |
11.133 | 2.940 | Kandi |
natitingou |
10.303 | 1.381 | Natitingou |
malanville |
11.867 | 3.383 | Malanville |
abomey |
7.183 | 1.983 | Abomey |
porto-novo |
6.497 | 2.627 | Porto-Novo |
lokossa |
6.617 | 1.717 | Lokossa |
Matching is partial: 'Marché de Parakou' will be matched to 'parakou'. Unrecognized markets receive None for lat and lon. A missing column emits a warning and is ignored.
Returns: pd.DataFrame with added market_lat and market_lon columns.
std_coords(lat=None, lon=None)¶
Creates a geometry column containing shapely.geometry.Point objects from latitude and longitude columns.
df_norm = normalizer.std_coords(lat="latitude", lon="longitude")
# 'geometry' column added: Point(lon, lat) for each row
| Parameter | Type | Default | Description |
|---|---|---|---|
lat |
str or None |
None |
Latitude column name |
lon |
str or None |
None |
Longitude column name |
If lat or lon is None or refers to a missing column in the DataFrame, a log warning is emitted and the DataFrame is returned unchanged.
Rows with NaN latitude or longitude receive None in the geometry column.
If the shapely package is not installed, a warning is emitted and the DataFrame is returned unchanged.
Optional dependency:
shapely >= 2.0. Install it withpip install shapely>=2.0.
Returns: pd.DataFrame with added geometry column.
mappings()¶
Returns the full history of applied normalizations since Normalizer initialization.
normalizer.norm_cols()
normalizer.std_crops(col="culture")
normalizer.convert_units({"production": "tonne"})
hist = normalizer.mappings()
# {
# "colonnes": {"Rendement (kg)": "rendement_kg", ...},
# "unites": {"production": {"unite_source": "tonne", "facteur_kg": 1000.0, "unite_cible": "kg"}},
# "cultures": {"maïs": "maize", "Niébé": "cowpea"},
# "marches": {},
# "devises": {},
# }
| Key | Type | Content |
|---|---|---|
colonnes |
dict |
old_name -> new_name for each renamed column |
unites |
dict |
column -> {unite_source, facteur_kg, unite_cible} |
cultures |
dict |
local_name -> fao_code for each match found |
marches |
dict |
Empty in current version |
devises |
dict |
column -> {from, to, taux} |
Returns: dict (copy of internal history).
Full Chained Example¶
import kadi as kd
from kadi.kidas import Normalizer
df = kd.read_csv("recoltes_2024.csv")
normalizer = Normalizer(df)
df_norm = (
normalizer
.norm_cols()
.std_crops(col="culture")
.convert_units({"rendement_kg": "sac_100kg", "production": "tonne"})
.std_markets(col="marche")
.std_coords(lat="latitude", lon="longitude")
)
hist = normalizer.mappings()
print(f"Renamed columns: {len(hist['colonnes'])}")
print(f"Normalized crops: {len(hist['cultures'])}")
print(f"Converted units: {len(hist['unites'])}")
Usage in a Pipeline¶
Normalizer is used internally by Pipeline when adding a normalization step via add_step or normalize.
from kadi.kidas import Pipeline
df, report = (
Pipeline()
.add_source("recoltes_2024.csv")
.add_step("norm_cols")
.add_step("std_crops", col="culture")
.add_step("convert_units", unit_map={"rendement_kg": "sac_100kg"})
.run()
)
For pipeline documentation, see Pipeline.
Backward Compatibility¶
Legacy method names emit a DeprecationWarning and continue to function until KadiPy v2.0:
| Legacy Name (before v1.2.0) | New Name |
|---|---|
normalize_column_names() |
norm_cols() |
normalize_units() |
convert_units() |
normalize_currencies() |
convert_currency() |
normalize_crop_names() |
std_crops() |
normalize_market_names() |
std_markets() |
normalize_geometry() |
std_coords() |
get_normalization_mapping() |
mappings() |
Likewise, the class name DataNormalizer is an alias of Normalizer.
Normalizer ¶
Classe de normalisation des données agricoles pour le contexte béninois.
Fournit des méthodes de transformation pour uniformiser les conventions de dénomination, les unités de mesure, les devises, les noms de cultures et de marchés, et pour créer des géométries GPS.
Toutes les opérations sont tracées dans un mapping interne récupérable via mappings().
Attributs
df (pd.DataFrame): Le DataFrame en cours de normalisation. _mappings (dict): Historique des transformations appliquées.
Exemple
normalizer = Normalizer(df) df_norm = ( ... normalizer ... .norm_cols() ... .std_crops(col='culture') ... .convert_units(unit_map={'production': 'tonne'}) ... )
Source code in kadi/kidas/normalizer.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
__init__ ¶
Initialise le normaliseur avec le DataFrame à transformer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Le DataFrame source à normaliser. Une copie interne est créée pour préserver l'original. |
required |
Raises:
| Type | Description |
|---|---|
CleanError
|
Si l'argument fourni n'est pas un DataFrame. |
Source code in kadi/kidas/normalizer.py
norm_cols ¶
Normalise les noms de colonnes du DataFrame.
Convertit les noms de colonnes en snake_case en supprimant les accents, les espaces et les caractères spéciaux. Exemple : 'Température Min (°C)' → 'temperature_min_c'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
style
|
str
|
Style de nommage cible. Seul 'snake_case' est supporté actuellement. Par défaut 'snake_case'. |
'snake_case'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec les noms de colonnes normalisés. |
Source code in kadi/kidas/normalizer.py
convert_units ¶
Convertit les valeurs de colonnes numériques vers le kilogramme.
Applique les facteurs de conversion définis dans le dictionnaire de référence _FACTEURS_UNITE_KG pour chaque colonne spécifiée.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_map
|
dict[str, str]
|
Dictionnaire nom_colonne → unité_source. Exemple : {'production': 'tonne', 'recolte': 'sac_100kg'}. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec les valeurs converties en kg. |
Raises:
| Type | Description |
|---|---|
CleanError
|
Si une unité source est inconnue. |
Source code in kadi/kidas/normalizer.py
convert_currency ¶
convert_currency(col: str, from_: str = 'XOF', to: str = 'XOF', date: Optional[str] = None, **kwargs) -> pd.DataFrame
Convertit les valeurs monétaires d'une colonne.
Note : Dans sa version actuelle, cette méthode applique un taux de change fixe. Une intégration avec une API de change peut être ajoutée en Phase 2 du module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Nom de la colonne à convertir. |
required |
from_
|
str
|
Devise source (ex: 'USD', 'XOF', 'EUR'). Par défaut 'XOF'. Alias accepté : from_currency= (rétrocompat.). |
'XOF'
|
to
|
str
|
Devise cible. Par défaut 'XOF'. Alias accepté : to_currency= (rétrocompat.). |
'XOF'
|
date
|
str | None
|
Date de référence pour le taux de change (format 'YYYY-MM-DD'). None pour le taux actuel. Alias accepté : exchange_date= (rétrocompat.). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec la colonne convertie. |
Source code in kadi/kidas/normalizer.py
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
std_crops ¶
Normalise les noms de cultures vers un standard international.
Utilise le dictionnaire de référence _CULTURE_ALIASES pour mapper les noms locaux béninois (avec ou sans accents) vers les codes FAO.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Nom de la colonne contenant les noms de cultures. |
required |
std
|
str
|
Standard cible. 'fao' utilise les codes officiels FAO (ex: 'maize', 'cowpea'). Par défaut 'fao'. Alias accepté : target_standard= (rétrocompatibilité). |
'fao'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec la colonne de cultures normalisée. |
Source code in kadi/kidas/normalizer.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | |
std_markets ¶
Normalise les noms de marchés et assigne les coordonnées GPS.
Mappe les noms de marchés béninois vers leur forme officielle et ajoute les colonnes 'market_lat' et 'market_lon' correspondantes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Nom de la colonne contenant les noms de marchés. |
required |
region
|
str
|
Région de référence pour le dictionnaire de marchés. Par défaut 'benin'. |
'benin'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec les noms de marchés normalisés et les colonnes 'market_lat' / 'market_lon' ajoutées. |
Source code in kadi/kidas/normalizer.py
std_coords ¶
Crée une colonne 'geometry' contenant des points GPS shapely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat
|
str | None
|
Nom de la colonne de latitude. Alias accepté : lat_col= (rétrocompatibilité). |
None
|
lon
|
str | None
|
Nom de la colonne de longitude. Alias accepté : lon_col= (rétrocompatibilité). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame avec la colonne 'geometry' ajoutée. Les lignes avec lat ou lon manquante ont geometry = None. |
Source code in kadi/kidas/normalizer.py
mappings ¶
Retourne l'historique complet des normalisations appliquées.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionnaire structuré par type de normalisation : - 'colonnes' (dict) : ancien → nouveau nom de colonne. - 'unites' (dict) : colonne → {unite_source, facteur_kg, unite_cible}. - 'cultures' (dict) : nom_local → code_fao. - 'marches' (dict) : nom_local → coordonnées. - 'devises' (dict) : colonne → {from, to, taux}. |
Source code in kadi/kidas/normalizer.py
__getattr__ ¶
Intercepte les anciens noms de méthodes pour la rétrocompatibilité.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Nom de la méthode demandée. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
callable |
La méthode correspondant au nouveau nom. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
Si le nom n'est pas un alias connu. |