Modeling_Tool.Core¶
Foundation layer: binning, model registry, sample-weight helpers, the ODPS client, the parallel apply engine, ProcCompare, encryption, JSON conversion, slope computation, and general utilities. The other subpackages build on it. At import time it imports none of them (see the import rules).
Sample Weights: sample_weight_utils¶
Resolves weight_col / sample_weight (and the wgt_col / wgt aliases) for uniform use by the Model and Eval layers.
sample_weight_utils
¶
Sample-weight resolution and weighted aggregation helpers.
resolve_sample_weight
¶
resolve_sample_weight(data=None, weight_col=None, sample_weight=None, expected_len=None, wgt=None, wgt_col=None)
Resolve sample weights from a DataFrame column or array.
Accepts weight_col / wgt_col and sample_weight / wgt aliases.
Returns None when no weight source is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or None
|
Frame that holds the weight column; required when |
None
|
weight_col
|
str or None
|
Name of the weight column in |
None
|
sample_weight
|
array - like or None
|
Weights given directly, one per row. |
None
|
expected_len
|
int or None
|
Required length of the weight vector; None skips the length check. |
None
|
wgt
|
array - like or None
|
Alias of |
None
|
wgt_col
|
str or None
|
Alias of |
None
|
Returns:
| Type | Description |
|---|---|
ndarray or None
|
The validated 1-D float weight vector (see |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both a column and an array are given, if a column is given without |
KeyError
|
If the weight column is not in |
Source code in Modeling_Tool/Core/sample_weight_utils.py
validate_sample_weight
¶
Validate and return a 1-D float numpy weight vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
array - like
|
Candidate weights, converted with |
required |
expected_len
|
int or None
|
Required length; None skips the length check. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The weights as a 1-D float array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the array is not 1-dimensional, has a length other than |
Source code in Modeling_Tool/Core/sample_weight_utils.py
weighted_sum
¶
Weighted sum of values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
array - like
|
Values to add up. |
required |
weights
|
array - like
|
Weights, one per value; no validation is done. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in Modeling_Tool/Core/sample_weight_utils.py
weighted_mean
¶
Weighted mean; returns NaN when total weight is zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
array - like
|
Values to average. |
required |
weights
|
array - like
|
Weights, one per value; no validation is done. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in Modeling_Tool/Core/sample_weight_utils.py
weighted_rate
¶
Weighted rate of True / 1 values in mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
array - like
|
Boolean (or 0/1) flags, one per row. |
required |
weights
|
array - like
|
Weights, one per row; no validation is done. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The share of the total weight that falls on flagged rows; NaN when the weights sum to zero. |
Source code in Modeling_Tool/Core/sample_weight_utils.py
Binning: Binning_Tool¶
Binning_Tool
¶
NumVarBinning
¶
Compute the cut-point sequence of a numeric variable from the number of bins and the binning method.
The cut points are computed from the specified number of bins; the binning methods are "equal-width" and "equal-frequency": (1) When the number of bins is not smaller than the number of unique values of the variable, the cut-point sequence is the sequence of unique values (2) When the number of bins is smaller than the number of unique values, either "equal-width" or "equal-frequency" binning can be chosen
If values that must be binned separately are specified: (1) Add the values to the cut-point sequence (2) Add the upper bound of each value = value + 0.1**(precision+1) to the cut-point sequence
Cut-point precision: (1) If the variable takes integer values, the precision is 1 decimal place (2) If the variable takes floating-point values, the precision is the number of decimal places of the input
For better generalization, the minimum of the cut-point sequence is replaced with -inf and +inf is added as the maximum
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name |
required |
spec_values
|
list
|
Special values to be binned separately |
None
|
spec_digit
|
int
|
Number of decimal places kept for the upper bound of a special cut point; fixed to 1 if the variable is an integer, otherwise equal to spec_digit |
3
|
Examples:
>>> nvb = NumVarBinning(var_name='income', spec_values=[-9999])
>>> binning = nvb.equi_binning(df, bins=10)
Source code in Modeling_Tool/Core/Binning_Tool.py
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 | |
calc_equi_cutpoints
¶
Compute the cut-point sequence of a numeric variable from the number of bins and the equi-binning method.
-
Compute the cut points from the specified number of bins; the binning methods are "equal-width" and "equal-frequency" (1) When the number of bins is not smaller than the number of unique values of the variable, the cut-point sequence is the sequence of unique values (2) When the number of bins is smaller than the number of unique values, either "equal-width" or "equal-frequency" binning can be chosen
-
If values that must be binned separately are specified: (1) Add the values to the cut-point sequence; (2) Add the upper bound of each value = value + 0.1**(precision+1) to the cut-point sequence;
-
Cut-point precision: (1) If the variable takes integer values, the precision is 1 decimal place (2) If the variable takes floating-point values, the precision is the number of decimal places of the input
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
bins
|
int
|
Number of bins |
10
|
equi_method
|
string
|
Binning method, candidate values {"equid": equal-width, "equif": equal-frequency} |
"equif"
|
Returns:
| Name | Type | Description |
|---|---|---|
cut_points |
array
|
Cut-point sequence |
Source code in Modeling_Tool/Core/Binning_Tool.py
modify_cutpoints
¶
Adjust the cut-point sequence.
-
Cut-point precision: (1) If the variable takes integer values, the precision is 1 decimal place (2) If the variable takes floating-point values, the precision is the number of decimal places of the input
-
Filter out cut points that fall outside the value range of the variable, and remove duplicates
-
For better generalization, the minimum of the cut-point sequence is replaced with -inf and +inf is added as the maximum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
points
|
array - like
|
Cut-point sequence |
required |
Returns:
| Name | Type | Description |
|---|---|---|
cut_points |
array
|
Adjusted cut-point sequence |
Source code in Modeling_Tool/Core/Binning_Tool.py
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 | |
apt_binning
¶
Bin the variable using the specified cut-point sequence.
Cut-point precision: (1) If the variable takes integer values, the precision is 1 decimal place (2) If the variable takes floating-point values, the precision is the number of decimal places of the input
Filter out cut points that fall outside the value range of the variable
For better generalization, the minimum of the cut-point sequence is replaced with -inf and +inf is added as the maximum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
points
|
array - like
|
Cut-point sequence |
required |
modify
|
bool
|
Whether to adjust the cut-point sequence |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
binning_series |
Categorical
|
Binned series |
Source code in Modeling_Tool/Core/Binning_Tool.py
equi_binning
¶
Compute the cut-point sequence of a numeric variable from the number of bins and the equi-binning method, then bin the variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
bins
|
int
|
Number of bins |
10
|
equi_method
|
string
|
Binning method, candidate values {"equid": equal-width, "equif": equal-frequency} |
"equif"
|
Returns:
| Name | Type | Description |
|---|---|---|
binning_series |
Categorical
|
Binned series |
Source code in Modeling_Tool/Core/Binning_Tool.py
apply_binning
¶
Bin the variable using the saved cut-point sequence.
Bin new data using the cut points previously computed by methods such as equi_binning or auto_binning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
Returns:
| Name | Type | Description |
|---|---|---|
binning_series |
Categorical
|
Binned series |
Source code in Modeling_Tool/Core/Binning_Tool.py
auto_binning
¶
auto_binning(df, tgt_name, max_bins=10, min_prop_in_bin=0.05, equi_bins=200, equi_method='equif', init_points=None, binning_criteria='chi2', chi2_p=0.95)
Automatic binning based on the chi-square test.
Using a distribution-distance measure, automatically derive the bin sequence for the given maximum number of bins and minimum number of samples per bin. Steps: 1. Use the initial binning method to complete the initial binning 2. Based on the distribution-distance measure, compute the sample size and within-bin distribution distance of each initial bin, as well as the gain in distance difference relative to the original bins after merging adjacent bins 3. Keep merging bins whose sample size does not meet the minimum-samples-per-bin requirement and bins whose merge with an adjacent bin yields a larger distance-difference gain, until the maximum number of bins and the minimum number of samples per bin are satisfied 4. Generate the binned variable series from the final binning result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
tgt_name
|
str
|
Target variable name |
required |
max_bins
|
int
|
Maximum number of bins |
10
|
min_prop_in_bin
|
float
|
Minimum proportion of samples per bin |
0.05
|
equi_bins
|
int
|
Number of initial bins |
200
|
equi_method
|
string
|
Initial binning method, candidate values {"equid": equal-width, "equif": equal-frequency} |
"equif"
|
init_points
|
array - like
|
Initial cut-point sequence; if not None, equi_bins and equi_method are ignored |
None
|
binning_criteria
|
string
|
Binning criterion, candidate values {"chi2": "chi-square value"} |
"chi2"
|
chi2_p
|
float
|
Probability used to compute the quantile of the chi-square distribution with 1 degree of freedom. When the chi-square value of adjacent bins is smaller than this quantile, the bins are considered not independent and are merged; a larger value therefore makes the independence test stricter |
0.95
|
Returns:
| Name | Type | Description |
|---|---|---|
binning_series |
Categorical
|
Binned series |
Source code in Modeling_Tool/Core/Binning_Tool.py
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 | |
Binning
¶
Unified binning class.
Integrate several binning methods, such as quick binning and chi-square binning, behind a unified interface for binning data. Supports equal-frequency/equal-width binning, decision-tree binning, automatic chi-square binning, and other strategies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table (it is copied; the original data is not modified) |
required |
column
|
str
|
Name of the column to bin |
required |
tgt_name
|
str
|
Target variable name (required for chi-square binning) |
None
|
nbins
|
int
|
Number of bins |
10
|
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin |
0.05
|
include_missing
|
bool
|
Whether to include missing values |
True
|
equal_freq
|
bool
|
True for equal-frequency binning, False for equal-width binning |
True
|
bin_colnames
|
tuple
|
Tuple of the column names of the binning results |
("_bin_num", "_bin_range")
|
ascending
|
bool
|
Whether the bin order is ascending |
True
|
right
|
bool
|
Whether the intervals are closed on the right |
True
|
include_lowest
|
bool
|
Whether to include the lowest value |
False
|
tree_binning
|
bool
|
Whether to use decision-tree binning |
False
|
chi2_method
|
bool
|
Whether to use chi-square binning |
False
|
chi2_p
|
float
|
Significance level of the chi-square test |
0.95
|
init_equi_bins
|
int
|
Number of initial equal-frequency bins |
200
|
fillna
|
any
|
Fill value for missing values |
-999999
|
spec_values
|
list
|
List of special values |
[]
|
random_state
|
int
|
Random seed |
42
|
Attributes:
| Name | Type | Description |
|---|---|---|
result |
DataFrame
|
Binning result data |
bin_edges |
ndarray
|
Array of bin edges |
Examples:
>>> binner = Binning(data, column='income', tgt_name='default', nbins=10)
>>> binner.run()
>>> result, edges = binner.get_result()
>>> # Use chi-square binning
>>> binner = Binning(data, column='income', tgt_name='default',
... nbins=10, chi2_method=True, chi2_p=0.95)
>>> binner.run()
Source code in Modeling_Tool/Core/Binning_Tool.py
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 | |
run_quick_binning
¶
Run quick binning.
Run equal-frequency or equal-width binning according to the configured parameters and add the result to the data.
Returns:
| Type | Description |
|---|---|
self
|
Returns itself to allow method chaining |
Source code in Modeling_Tool/Core/Binning_Tool.py
run_chi2_binning
¶
Run chi-square binning.
Building on quick binning, further apply the chi-square test to optimize the bins automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_points
|
array - like
|
Initial bin edges, used as the starting point of chi-square binning |
None
|
Returns:
| Type | Description |
|---|---|
self
|
Returns itself to allow method chaining |
Source code in Modeling_Tool/Core/Binning_Tool.py
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 | |
run
¶
Run the binning.
Run either quick binning or chi-square binning, depending on the chi2_method parameter.
Returns:
| Type | Description |
|---|---|
self
|
Returns itself to allow method chaining |
Source code in Modeling_Tool/Core/Binning_Tool.py
get_result
¶
Get the binning result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
return_edges
|
bool
|
Whether to return the bin edges |
True
|
Returns:
| Type | Description |
|---|---|
tuple or DataFrame
|
If return_edges is True, return the tuple (result, bin_edges); otherwise return only result |
Source code in Modeling_Tool/Core/Binning_Tool.py
get_max_nbins
¶
Compute the maximum number of bins from a given minimum bin proportion.
From the total number of records and the minimum bin proportion, compute the largest number of bins that still meets the minimum sample-size requirement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table |
required |
nbins
|
int
|
Desired number of bins |
required |
min_bin_prop
|
float
|
Minimum proportion of samples in each bin |
0.05
|
Returns:
| Type | Description |
|---|---|
int
|
Maximum feasible number of bins |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
get_decision_tree_binning_edges
¶
get_decision_tree_binning_edges(feature, target, max_leaf_nodes=5, min_samples_leaf=0.05, random_state=42, missing_ref_value=None, spec_values=[])
Find the optimal bins of a continuous variable using a decision tree.
Use a decision-tree classifier to find the optimal bin edges; suitable for automated binning of continuous variables. The algorithm handles missing values and special values automatically and returns suitable bin edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature
|
array - like
|
Continuous feature to bin, a pandas Series or a 1-D array |
required |
target
|
array - like
|
Target variable, a binary label (pandas Series or 1-D array) |
required |
max_leaf_nodes
|
int
|
Maximum number of leaf nodes of the decision tree, i.e. the maximum number of bins |
5
|
min_samples_leaf
|
float
|
Minimum sample fraction per leaf node; defaults to 0.05 (5%) |
0.05
|
random_state
|
int
|
Random seed to make the results reproducible |
42
|
missing_ref_value
|
any
|
Reference value for missing values; this value is treated as missing |
None
|
spec_values
|
list
|
List of special values; these values are binned separately |
[]
|
Returns:
| Name | Type | Description |
|---|---|---|
bin_edges |
list
|
List of bin edges |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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 | |
cre_pvt
¶
Create a pivot table with the variable as rows and the target variable as columns.
Build a per-bin statistics pivot table from the specified variable and target variable, containing the number of negative samples, the number of positive samples, the total number of samples, and the target rate of each bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Data table |
required |
var_name
|
str
|
Variable name (the grouping key) |
required |
tgt_name
|
str
|
Target variable name (binary label, 0 and 1) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
df_pvt |
DataFrame
|
Variable pivot table, containing the columns: - 0: number of negative samples - 1: number of positive samples - n: total number of samples - tr: target rate (proportion of positive samples) |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
merge_bins
¶
Merge variable bins based on position indices.
Merge the bins at the specified positions, compute the statistics after merging (sample counts, target rate, etc.), and update the chi-square values and target-rate differences.
Important: the index of df_pvt must not be reset
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_pvt
|
DataFrame
|
Variable pivot table generated by the cre_pvt function |
required |
ilocs
|
list
|
List of position indices to merge (e.g. [0,1] merges the first two bins) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
df_pvt_new |
DataFrame
|
Variable pivot table after merging |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
observed_laplace
¶
Apply a Laplace correction to the values of a contingency table.
Add a small amount (0.1**digit) to every cell of the contingency table to avoid chi-square test problems caused by zero counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observed
|
array_like
|
Contingency table (a 2-D array or similar structure) |
required |
digit
|
int
|
Number of decimal places of the small amount added to the observed values; if -1, the integer 1 is added |
6
|
Returns:
| Name | Type | Description |
|---|---|---|
obs_laplace |
ndarray
|
Contingency table after the Laplace correction |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
cat_2_list
¶
Convert a binned Categorical series to a list of edge values.
Extract all interval edges from Categorical data and return the de-duplicated list made up of all left and right edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bin_series
|
Categorical
|
Binned Categorical series |
required |
Returns:
| Type | Description |
|---|---|
list
|
List containing all interval edge values |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
get_bin_range
¶
Generate a list of interval string descriptions from the bin edges.
Convert a list of bin edges into a list of string descriptions with interval signs; supports custom open/closed interval signs and precision.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
array - like
|
List of bin edge values |
required |
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
ascending
|
bool
|
Whether to sort in ascending order |
False
|
left_sign
|
str
|
Left interval sign; '[' means inclusive, '(' means exclusive |
'('
|
right_sign
|
str
|
Right interval sign; ']' means inclusive, ')' means exclusive |
']'
|
Returns:
| Type | Description |
|---|---|
list
|
List of interval string descriptions |
Examples:
>>> edges = [0, 10, 20, 30]
>>> ranges = get_bin_range(edges, precision=0, ascending=True)
['[0, 10]', '[10, 20]', '[20, 30]']
Source code in Modeling_Tool/Core/Binning_Tool.py
get_bin_range_list
¶
Convert a column of bin interval strings to a list of edge values.
Parse the bin interval string column of a DataFrame (such as "[0, 10)", "(10, 20]"), extract all unique edge values, and return them sorted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the bin interval column |
required |
col
|
str
|
Name of the bin interval column |
"_bin_range"
|
Returns:
| Type | Description |
|---|---|
list
|
De-duplicated, sorted list of edge values |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
chi2_auto_binning
¶
Automatic binning based on the chi-square test.
Use the chi-square test to decide whether adjacent bins should be merged, iterating through the following steps: 1. First handle the head and tail bins whose sample size does not meet the minimum requirement 2. Then handle the middle bins with insufficient sample size 3. Finally, merge adjacent bins that are not independent according to the chi-square test
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_pvt
|
DataFrame
|
Variable pivot table generated by the cre_pvt function, containing the columns: 0, 1, n, tr |
required |
max_bins
|
int
|
Maximum number of bins |
required |
min_cnt_in_bin
|
int
|
Minimum number of samples per bin |
required |
p
|
float
|
Probability used to compute the quantile of the chi-square distribution with 1 degree of freedom. When the chi-square value of adjacent bins is smaller than this quantile, the bins are considered not independent and are merged. The larger the value, the stricter the independence test |
0.95
|
Returns:
| Name | Type | Description |
|---|---|---|
df_pvt |
DataFrame
|
Variable pivot table after merging |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 | |
quick_binning
¶
quick_binning(data, column, labels=None, nbins=10, precision=5, equal_freq=True, right=True, include_lowest=False, min_bin_prop=0.05, ascending=True, include_missing=False, tree_binning=False, target=None, random_state=42, fillna=-999999, spec_values=[])
Quick binning function.
Quickly bin the data with equal-frequency or equal-width binning; several binning strategies are supported: - Equal-frequency binning: split by quantiles so that every bin has a similar number of samples - Equal-width binning: split evenly by value intervals - Decision-tree binning: use a decision tree to find the optimal cut points
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table |
required |
column
|
str
|
Name of the column to bin |
required |
labels
|
array - like
|
Custom bin labels |
None
|
nbins
|
int or list / tuple
|
Number of bins (an integer) or the specified bin edges (a list or tuple) |
10
|
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
equal_freq
|
bool
|
True for equal-frequency binning, False for equal-width binning |
True
|
right
|
bool
|
Whether the intervals are closed on the right |
True
|
include_lowest
|
bool
|
Whether to include the lowest value |
False
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin |
0.05
|
ascending
|
bool
|
Whether the bin order is ascending |
True
|
include_missing
|
bool
|
Whether to include missing values |
False
|
tree_binning
|
bool
|
Whether to use decision-tree binning |
False
|
target
|
str
|
Target variable name (required for decision-tree binning) |
None
|
random_state
|
int
|
Random seed |
42
|
fillna
|
any
|
Fill value for missing values |
-999999
|
spec_values
|
list
|
List of special values; each is placed in its own bin |
[]
|
Returns:
| Name | Type | Description |
|---|---|---|
binned |
Categorical
|
Binned series |
bin_edges |
ndarray
|
Array of bin edges |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 | |
chi2_binning
¶
chi2_binning(data, column, nbins=10, precision=5, min_bin_prop=0.05, tgt_name=None, include_missing=True, equal_freq=True, bin_colnames=('_bin_num', '_bin_range'), ascending=True, chi2_p=0.95, init_equi_bins=100, fillna=-999999, spec_values=[], init_points=None)
Binning function based on the chi-square test.
Use the chi-square test to find the optimal bin edges automatically: the test decides whether adjacent bins should be merged, yielding statistically significant bins in the end.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table |
required |
column
|
str
|
Name of the column to bin |
required |
nbins
|
int
|
Maximum number of bins |
10
|
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin |
0.05
|
tgt_name
|
str
|
Target variable name (binary label, 0 and 1) |
None
|
include_missing
|
bool
|
Whether to include missing values |
True
|
equal_freq
|
bool
|
True for equal-frequency binning, False for equal-width binning |
True
|
bin_colnames
|
tuple
|
Tuple of the column names of the binning results |
("_bin_num", "_bin_range")
|
ascending
|
bool
|
Whether the bin order is ascending |
True
|
chi2_p
|
float
|
Significance level of the chi-square test |
0.95
|
init_equi_bins
|
int
|
Number of initial equal-frequency bins |
100
|
fillna
|
any
|
Fill value for missing values |
-999999
|
spec_values
|
list
|
List of special values |
[]
|
init_points
|
array - like
|
Initial bin edges, used as the starting point of chi-square binning |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
(result, bin_edges) - the binning result DataFrame and the array of bin edges |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 | |
run_binning
¶
run_binning(data, column, nbins=10, precision=5, min_bin_prop=0.05, include_missing=True, equal_freq=True, bin_colnames=('bin_num', 'bin_range'), ascending=False, right=True, include_lowest=False, tree_binning=False, target=None, random_state=42, spec_values=[], fillna=-999999)
General-purpose binning function supporting equal-frequency or equal-width binning.
Bin a numeric variable with a range of configuration options and return the binned data together with the bin edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the column to bin |
required |
nbins
|
int
|
Number of bins |
10
|
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin |
0.05
|
include_missing
|
bool
|
Whether to include missing values |
True
|
equal_freq
|
bool
|
True for equal-frequency binning, False for equal-width binning |
True
|
bin_colnames
|
tuple
|
Tuple of the column names of the binning results |
("bin_num", "bin_range")
|
ascending
|
bool
|
Whether the bin order is ascending |
False
|
right
|
bool
|
Whether the intervals are closed on the right |
True
|
include_lowest
|
bool
|
Whether to include the lowest value |
False
|
tree_binning
|
bool
|
Whether to use decision-tree binning |
False
|
target
|
str
|
Target variable name (required for decision-tree binning) |
None
|
random_state
|
int
|
Random seed |
42
|
spec_values
|
list
|
List of special values |
[]
|
fillna
|
scalar
|
Sentinel value that holds the missing values in their own bin when |
-999999
|
Returns:
| Type | Description |
|---|---|
tuple
|
(data, bin_edges) - the data with the binning columns added and the array of bin edges |
Examples:
Source code in Modeling_Tool/Core/Binning_Tool.py
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 | |
super_binning
¶
super_binning(data, score, dep, nbins=10, precision=5, min_bin_prop=0.05, include_missing=True, equal_freq=True, chi2_method=False, chi2_p=0.95, init_equi_bins=2000, fillna=-999999, spec_values=[], tree_binning=False, random_state=42, return_edges=False, ascending=True, bin_colnames=('_bin_num', '_bin_range'))
Super binning function that combines several binning strategies.
Provide a unified binning interface with two modes, basic binning and chi-square binning, and automatically choose a suitable binning strategy from the parameter configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table |
required |
score
|
str
|
Name of the score/numeric column to bin |
required |
dep
|
str
|
Target variable name (binary label, 0 and 1) |
required |
nbins
|
int
|
Maximum number of bins |
10
|
precision
|
int
|
Precision of the edge values (number of decimal places) |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin |
0.05
|
include_missing
|
bool
|
Whether to include missing values |
True
|
equal_freq
|
bool
|
True for equal-frequency binning, False for equal-width binning |
True
|
chi2_method
|
bool
|
Whether to refine the bins with chi-square binning |
False
|
chi2_p
|
float
|
Significance level of the chi-square test |
0.95
|
init_equi_bins
|
int
|
Number of initial equal-frequency bins (before chi-square binning) |
2000
|
fillna
|
any
|
Fill value for missing values |
-999999
|
spec_values
|
list
|
List of special values |
[]
|
tree_binning
|
bool
|
Whether to use decision-tree binning |
False
|
random_state
|
int
|
Random seed |
42
|
return_edges
|
bool
|
Whether to return the bin edges |
False
|
ascending
|
bool
|
Whether the bin order is ascending |
True
|
bin_colnames
|
tuple
|
Tuple of the column names of the binning results |
("_bin_num", "_bin_range")
|
Returns:
| Type | Description |
|---|---|
DataFrame or tuple
|
If return_edges is False, return the binning result data If return_edges is True, return the tuple (result, edges) |
Examples:
>>> # Chi-square binning
>>> result, edges = super_binning(data, score='income', dep='default',
... nbins=10, chi2_method=True, return_edges=True)
Source code in Modeling_Tool/Core/Binning_Tool.py
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 | |
Model Registry: Model_Registry_Tool¶
save_model, load_model, and load_model_metadata are also importable from Modeling_Tool.
Model_Registry_Tool
¶
Model artifact persistence helpers with metadata support.
This module provides the public save_model / load_model helpers used by
Modeling_Tool. It stays backward compatible with legacy files that contain
only a raw joblib object while adding an SMF artifact envelope for model version
and deployment metadata.
make_model_artifact
¶
make_model_artifact(model, metadata: Optional[Dict[str, Any]] = None, feature_cols=None, woe_mapping_path: Optional[str] = None, train_window: Optional[Dict[str, Any]] = None, metrics: Optional[Dict[str, Any]] = None, model_name: Optional[str] = None, model_version: Optional[str] = None)
Create an in-memory SMF model artifact without writing it to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
Model object to wrap. It is referenced, not copied. |
required |
metadata
|
dict
|
Additional or overriding metadata fields. They are applied last, so a key given here replaces the generated
value of the same name (including |
None
|
feature_cols
|
list - like
|
Training feature list. A single string is stored as a one-element list and any other iterable is stored as a list. |
None
|
woe_mapping_path
|
str
|
Path to the WOE mapping table used by the model. |
None
|
train_window
|
dict
|
Training / validation / OOT sample window metadata. |
None
|
metrics
|
dict
|
Evaluation metrics such as AUC / KS by dataset. |
None
|
model_name
|
str
|
Business model name. |
None
|
model_version
|
str
|
Business model version. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
The artifact envelope with the keys |
Source code in Modeling_Tool/Core/Model_Registry_Tool.py
save_model
¶
save_model(model, filename, metadata: Optional[Dict[str, Any]] = None, feature_cols=None, woe_mapping_path: Optional[str] = None, train_window: Optional[Dict[str, Any]] = None, metrics: Optional[Dict[str, Any]] = None, model_name: Optional[str] = None, model_version: Optional[str] = None, include_metadata: bool = True)
Save a model, optionally wrapped with standard SMF metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
Model object to persist. |
required |
filename
|
str or path - like
|
Destination path. |
required |
metadata
|
dict
|
Additional or overriding metadata fields. |
None
|
feature_cols
|
list - like
|
Training feature list. |
None
|
woe_mapping_path
|
str
|
Path to the WOE mapping table used by the model. |
None
|
train_window
|
dict
|
Training / validation / OOT sample window metadata. |
None
|
metrics
|
dict
|
Evaluation metrics such as AUC / KS by dataset. |
None
|
model_name
|
str
|
Business model name. |
None
|
model_version
|
str
|
Business model version. |
None
|
include_metadata
|
bool
|
If True, save an SMF artifact envelope. If False, save the raw model object exactly like the legacy helper. |
True
|
Returns:
| Type | Description |
|---|---|
int
|
0 on success. |
Source code in Modeling_Tool/Core/Model_Registry_Tool.py
load_model
¶
Load a legacy model or an SMF model artifact.
By default this keeps backward compatibility and returns only the model
object. Set return_metadata=True to receive (model, metadata).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str or path - like
|
Path of a file written by |
required |
return_metadata
|
bool
|
If False, return only the model object. If True, return a |
False
|
Returns:
| Type | Description |
|---|---|
object or tuple
|
The model object, or |
Notes
The file is read with joblib.load, which unpickles it: load only files from a trusted source.
Source code in Modeling_Tool/Core/Model_Registry_Tool.py
load_model_metadata
¶
Load only metadata from an SMF model artifact.
Legacy raw-model files return an empty dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str or path - like
|
Path of a file written by |
required |
Returns:
| Type | Description |
|---|---|
dict
|
The metadata dict stored in the artifact, or an empty dict |
Notes
The whole file is deserialized with joblib.load, model included, so this is not cheaper than load_model,
and the same trust requirement applies: load only files from a trusted source.
Source code in Modeling_Tool/Core/Model_Registry_Tool.py
ODPS Client: ODPS_Tool¶
Needs the odps extra, and the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables
when you construct ODPSRunner. See ODPS Data Extraction.
ODPS_Tool
¶
ODPSRunner
¶
Bases: object
Source code in Modeling_Tool/Core/ODPS_Tool.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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 | |
run_sql
¶
Run SQL and download the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
str
|
A single SQL statement. |
required |
to_df
|
bool
|
Whether to load the result into memory and return it as a |
True
|
n_process
|
int
|
Number of parallel processes for |
1
|
csv_path
|
str
|
Path of a local CSV file to save the result to. Independent of |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The full data when |
Notes
- The execution phase (execute_sql) runs only once, with no retries.
- The download phase (to_pandas + to_csv) retries up to 6 times, which covers transient network failures.
- When the SQL returns more than 200 columns, a thread-safe wide-schema patch automatically patches the ODPS Tunnel to prevent HTTP 414 (URI too long).
Examples:
>>> odps = ODPSRunner()
>>> df = odps.run_sql("SELECT * FROM dual LIMIT 10") # DataFrame only
>>> df = odps.run_sql("SELECT * FROM dual LIMIT 10", csv_path="x.csv") # DataFrame + CSV
>>> _ = odps.run_sql("SELECT * FROM dual LIMIT 10", to_df=False, # CSV only
... csv_path="x.csv")
>>> _ = odps.run_sql("CREATE TABLE t AS SELECT 1") # execute only, no download
Source code in Modeling_Tool/Core/ODPS_Tool.py
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 | |
download_table
¶
Read table data into a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_name
|
str
|
Table name |
required |
partition
|
dict
|
Partition, e.g. 'dt=2022-01-01,taino=0' |
None
|
n_process
|
int
|
Number of processes used to convert the query data to a pandas.DataFrame |
1
|
csv_path
|
str
|
Path of the CSV file to save the query data to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
Result data of the SQL query |
Source code in Modeling_Tool/Core/ODPS_Tool.py
cre_table_schema
staticmethod
¶
Infer an ODPS table schema from the dtypes of a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Frame whose columns become the table columns. |
required |
partition_name
|
str or None
|
Name of a column of |
None
|
Returns:
| Type | Description |
|---|---|
Schema
|
One column per DataFrame column (bool -> boolean, integer -> bigint, float32 -> float, other floats ->
double, datetime -> datetime, string, object and category -> string) and, when |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a column has a dtype without an ODPS mapping (for example complex or timedelta). |
Source code in Modeling_Tool/Core/ODPS_Tool.py
upload_df
¶
Upload a dataset to MaxCompute and create a new table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataset to upload. |
required |
table_name
|
str
|
Name of the table to create or replace. |
required |
table_schema
|
Schema or None
|
Table schema. When None, the schema is inferred from the dtypes of |
None
|
partition
|
str or None
|
Partition spec to write the data to (for example |
None
|
atomic
|
bool
|
When |
True
|
Source code in Modeling_Tool/Core/ODPS_Tool.py
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 | |
insert_df
¶
Insert a dataset into an existing MaxCompute table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Dataset to insert. |
required |
table_name
|
str
|
Name of the existing table. |
required |
overwrite
|
bool
|
Whether to replace the existing data: the target partition is replaced when |
True
|
partition
|
str or None
|
Partition spec to write to (for example |
None
|
atomic
|
bool
|
Only used together with |
True
|
Notes
If the table has a py_inserttime column that df lacks, it is filled with the current time.
Source code in Modeling_Tool/Core/ODPS_Tool.py
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 | |
ODPS Concurrency: Parallel_ODPS_Manager¶
Parallel_ODPS_Manager
¶
ParallelODPSConfig
dataclass
¶
Settings of a ParallelODPSManager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unique_key
|
str or None
|
Column whose hash splits a pulled query into chunks ( |
None
|
chunk_size
|
int or None
|
Rows per chunk. |
None
|
n_chunks
|
int or None
|
Number of chunks. |
None
|
n_jobs
|
int
|
Number of parallel workers; must be positive. |
3
|
backend
|
('thread', 'process', 'sequential')
|
Execution backend of the chunk workers. With |
"thread"
|
pull_split_strategy
|
('auto', 'hash', 'row_number')
|
How |
"auto"
|
row_number_order_by
|
str or None
|
|
None
|
row_number_col
|
str
|
Name of the helper row-number column of the staging table; it is dropped from the pulled data. Must not be empty. |
"__smf_parallel_odps_rn__"
|
validate_unique_key
|
bool
|
In hash mode, run a |
True
|
chunk_filter_key
|
str
|
Name of the placeholder that the SQL template must contain ( |
"chunk_filter"
|
tmp_dir
|
Path or str
|
Local folder for chunk files; it is created when needed. |
Path("data/_chunks")
|
tmp_table_prefix
|
str
|
Prefix of the temporary ODPS tables (the staging table of |
"tmp_parallel_odps"
|
cleanup_tmp
|
bool
|
Drop the temporary ODPS tables when the run ends. |
True
|
keep_tmp_on_error
|
bool
|
Keep the temporary tables when the run fails, for debugging. Only relevant when |
False
|
Source code in Modeling_Tool/Core/Parallel_ODPS_Manager.py
ParallelODPSManager
¶
Parallel ODPS pull/push helper built on ODPSRunner and ParallelApplyEngine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ParallelODPSConfig
|
Settings of the manager. |
required |
odps_runner
|
ODPSRunner or None
|
Client used to run the SQL; None creates an |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configuration is invalid: an unknown |
Source code in Modeling_Tool/Core/Parallel_ODPS_Manager.py
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 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 | |
pull
¶
pull(sql_path: str, out_path: str, count_query: str | None = None, **template_kwargs: Any) -> dict[str, Any]
Pull a large query in concurrent chunks and merge them into one local CSV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql_path
|
str
|
Path of a SQL template file. It must contain the |
required |
out_path
|
str
|
Local CSV file to write. Its folder is created and an existing file is replaced. |
required |
count_query
|
str or None
|
SQL that returns the total row count in its first cell. It is only used when |
None
|
**template_kwargs
|
Any
|
Values for the other placeholders of the SQL template. |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the template lacks the placeholder, neither |
Source code in Modeling_Tool/Core/Parallel_ODPS_Manager.py
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 | |
push
¶
push(data: DataFrame | str | Path, target_table: str, write_mode: WriteMode | str | None = None) -> dict[str, Any]
Upload a DataFrame or CSV file in concurrent chunks and write them into one ODPS table.
Every chunk is uploaded to a temporary table; the target table is then created or filled from all of them with
UNION ALL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
(DataFrame, str or Path)
|
The rows to upload, or the path of a CSV file (read in chunks and copied to |
required |
target_table
|
str
|
Name of the table to write. |
required |
write_mode
|
('overwrite', 'append')
|
Required despite the default None. |
"overwrite"
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
FileNotFoundError
|
If a CSV path does not exist. |
RuntimeError
|
If any chunk fails to upload. |
Source code in Modeling_Tool/Core/Parallel_ODPS_Manager.py
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 | |
Parallel Apply Engine: Parallel_Engine¶
Parallel_Engine
¶
ParallelApplyConfig
dataclass
¶
Settings of a ParallelApplyEngine run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split_axis
|
('row', 'column', 'chunk', 'auto')
|
How the work is divided. |
"row"
|
backend
|
('process', 'thread', 'sequential')
|
|
"process"
|
n_jobs
|
(int, str or None)
|
Number of workers: a positive integer, |
"auto"
|
chunk_size
|
int or None
|
Rows per row chunk, or columns per column chunk (not counting |
None
|
n_chunks
|
int or None
|
Number of chunks to make (at most the number of rows or columns). Cannot be combined with |
None
|
preserve_order
|
bool
|
Sort the chunk results by chunk id before they are combined. |
True
|
combine
|
('concat', 'list', 'dict', 'none')
|
How the chunk outputs become |
"concat"
|
concat_axis
|
(0, 1)
|
Axis of the |
0
|
pass_chunk_info
|
bool
|
When True the function also receives a |
False
|
timeout
|
float or None
|
Seconds to wait for the workers, passed to joblib. It has no effect on sequential runs. |
None
|
on_error
|
('raise', 'collect')
|
|
"raise"
|
validate_picklable
|
bool
|
With the process backend, check with cloudpickle before the run that the function and its arguments can be
serialized, and raise |
True
|
auto_probe
|
bool
|
Accepted but not used by the engine. |
False
|
random_state
|
int or None
|
Seed of the row sample that the |
None
|
required_cols
|
list of str
|
Columns added to every block of a column split. |
empty list
|
id_cols
|
list of str
|
Identifier columns added to every block of a column split (same effect as |
empty list
|
Source code in Modeling_Tool/Core/Parallel_Engine.py
ParallelApplyResult
dataclass
¶
Result of ParallelApplyEngine.run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
object
|
The combined output, as selected by |
required |
chunk_outputs
|
list
|
Outputs of the successful chunks (in chunk order when |
empty list
|
errors
|
DataFrame
|
One row per failed chunk when |
empty frame
|
summary
|
dict
|
Run statistics: |
empty dict
|
config
|
ParallelApplyConfig or None
|
The configuration the run used. |
None
|
split_axis_resolved
|
str or None
|
The axis that was used ( |
None
|
Source code in Modeling_Tool/Core/Parallel_Engine.py
ParallelApplyEngine
¶
Parallel function dispatcher for DataFrame and custom chunk workloads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ParallelApplyConfig or None
|
Settings of the engine; None uses |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a setting is invalid: an unknown |
Source code in Modeling_Tool/Core/Parallel_Engine.py
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 | |
run
¶
run(data: Any = None, func: Callable[..., Any] | None = None, func_args: Sequence[Any] = (), func_kwargs: dict[str, Any] | None = None, chunks: Sequence[Any] | None = None) -> ParallelApplyResult
Split the work, run func on every chunk, and combine the outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or None
|
Frame to split. It must be a DataFrame unless |
None
|
func
|
callable
|
Called as |
None
|
func_args
|
sequence
|
Extra positional arguments for |
()
|
func_kwargs
|
dict or None
|
Extra keyword arguments for |
None
|
chunks
|
sequence or None
|
The objects to process one by one; required when |
None
|
Returns:
| Type | Description |
|---|---|
ParallelApplyResult
|
The combined |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
KeyError
|
If |
Source code in Modeling_Tool/Core/Parallel_Engine.py
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 | |
parallel_apply
¶
parallel_apply(data: Any = None, func: Callable[..., Any] | None = None, func_args: Sequence[Any] = (), func_kwargs: dict[str, Any] | None = None, chunks: Sequence[Any] | None = None, **config_kwargs: Any) -> Any
Run a function in parallel and return the combined output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or None
|
Frame to split, as in |
None
|
func
|
callable or None
|
Function applied to every chunk; required. |
None
|
func_args
|
sequence
|
Extra positional arguments for |
()
|
func_kwargs
|
dict or None
|
Extra keyword arguments for |
None
|
chunks
|
sequence or None
|
Objects to process one by one when |
None
|
**config_kwargs
|
Any
|
Fields of |
{}
|
Returns:
| Type | Description |
|---|---|
object
|
Only the combined output ( |
Source code in Modeling_Tool/Core/Parallel_Engine.py
Dataset Comparison: Proc_Compare¶
Proc_Compare
¶
ProcCompareConfig
dataclass
¶
Settings of a ProcCompareEngine run (the keyword arguments of proc_compare).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Folder for the CSV files, the Excel report and the temporary files of CSV mode. |
"output/proc_compare"
|
write_outputs
|
bool
|
Write the six result tables as CSV files into |
True
|
write_excel
|
bool
|
Write the ExcelMaster report. |
False
|
left_name
|
str
|
Name of the left table, written to |
"left"
|
right_name
|
str
|
Name of the right table. |
"right"
|
key_cols
|
list of str or None
|
Key columns that align the two tables. Required unless |
None
|
row_order_compare
|
bool
|
Align the tables by row number when there is no key. |
False
|
compare_cols
|
list of str or None
|
Columns to compare; None compares every column that exists in both tables. |
None
|
ignore_cols
|
list of str
|
Columns excluded from the comparison. |
empty list
|
chunk_size
|
int
|
Rows read per chunk in CSV mode; must be positive. |
200000
|
n_partitions
|
int
|
Number of hash partitions in CSV mode; must be positive. |
16
|
backend
|
('sequential', 'thread', 'process')
|
How the CSV partitions are compared. |
"sequential"
|
compare_block_size
|
int
|
Columns compared per vectorized block; lower it for very wide tables to limit memory. It does not change the results. Must be positive. |
64
|
numeric_tol
|
float
|
Absolute numeric tolerance: two numbers match when |
1e-8
|
numeric_rtol
|
float
|
Relative numeric tolerance, applied to |
0.0
|
datetime_tol_seconds
|
float
|
Tolerance for datetime columns, in seconds. Must not be negative. |
0.0
|
datetime_cols
|
list of str
|
Columns to compare as datetimes (recommended in CSV mode, where the dtype cannot be inferred from the file). |
empty list
|
per_column_tolerance
|
dict
|
Per-column overrides of the tolerances: a number (absolute tolerance), or a dict with the keys |
empty dict
|
both_null_equal
|
bool
|
Count two nulls as consistent; with False they count as a mismatch. |
True
|
missing_values
|
list
|
Extra values (for example |
empty list
|
detail_mode
|
('top', 'full', 'none')
|
Which mismatched cells |
"top"
|
top_n
|
int
|
Number of cells kept when |
1000
|
duplicate_key_policy
|
('raise', 'first', 'all')
|
What to do with duplicated keys: |
"raise"
|
excel_output_path
|
str or None
|
Path of the Excel report; None uses |
None
|
max_excel_rows
|
int
|
Maximum number of rows written per Excel sheet. |
100000
|
Source code in Modeling_Tool/Core/Proc_Compare.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
ProcCompareResult
dataclass
¶
Result of ProcCompareEngine.run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coverage_summary
|
DataFrame
|
One row with the row counts of both tables, the common rows and the rows found on one side only. |
required |
schema_summary
|
DataFrame
|
One row per column of either table with its role, dtypes and comparison status. |
required |
column_summary
|
DataFrame
|
One row per compared column: counts of compared, equal, mismatching and null cells, and the mean and maximum absolute difference. |
required |
row_summary
|
DataFrame
|
One row per key: |
required |
cell_mismatches
|
DataFrame
|
One row per mismatching cell (limited by |
required |
duplicate_key_summary
|
DataFrame
|
One row per duplicated key and side; empty when there are no duplicates. |
required |
output_paths
|
dict
|
Table name to CSV path; empty unless |
empty dict
|
report_path
|
str or None
|
Path of the Excel report, or None when it was not written. |
None
|
Source code in Modeling_Tool/Core/Proc_Compare.py
ProcCompareEngine
¶
SAS proc_compare-like consistency checker for DataFrames and CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ProcCompareConfig or None
|
Settings; None uses |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a setting is invalid: |
Source code in Modeling_Tool/Core/Proc_Compare.py
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 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 | |
run
¶
run(left: DataFrame | str | Path, right: DataFrame | str | Path) -> ProcCompareResult
Compare two tables.
When either input is a CSV path the comparison runs in CSV mode (chunked reading and hash partitions); otherwise both frames are compared in memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
(DataFrame, str or Path)
|
The left table, or the path of a CSV file. |
required |
right
|
(DataFrame, str or Path)
|
The right table, or the path of a CSV file. |
required |
Returns:
| Type | Description |
|---|---|
ProcCompareResult
|
The six result tables, plus the CSV paths and the Excel report path when they were written. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
Source code in Modeling_Tool/Core/Proc_Compare.py
proc_compare
¶
proc_compare(left: DataFrame | str | Path, right: DataFrame | str | Path, **kwargs: Any) -> ProcCompareResult
Convenience wrapper around :class:ProcCompareEngine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
(DataFrame, str or Path)
|
The left table, or the path of a CSV file. |
required |
right
|
(DataFrame, str or Path)
|
The right table, or the path of a CSV file. |
required |
**kwargs
|
Any
|
Fields of |
{}
|
Returns:
| Type | Description |
|---|---|
ProcCompareResult
|
The result of |
Source code in Modeling_Tool/Core/Proc_Compare.py
Slope Computation: Slope_Tool¶
Slope_Tool
¶
SlopeCalculator
¶
Slope calculator.
Provide several methods to compute the linear-regression slope of a data column, supporting: - sklearn LinearRegression - scipy.stats.linregress - numpy.polyfit - manual least squares
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
data |
DataFrame
|
Input data |
column |
str
|
Column name |
y |
ndarray
|
Converted data array |
x |
ndarray
|
x-axis array (index) |
Examples:
>>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
>>> calc = SlopeCalculator(df, 'values')
>>> calc.calculate_sklearn()
1.0
>>> calc.calculate_scipy()
(1.0, 1.0, 9.999999999999996e-08, 0.0)
Source code in Modeling_Tool/Core/Slope_Tool.py
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 | |
calculate_sklearn
¶
Compute the slope using sklearn LinearRegression.
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
calculate_scipy
¶
Compute the slope using scipy.stats.linregress.
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple (slope, r_value, p_value, std_err) |
calculate_numpy
¶
Compute the slope using numpy.polyfit.
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
calculate_manual
¶
Compute the slope using manual least squares.
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
calculate_all
¶
Compute the slope using all methods.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with the results of each method |
Source code in Modeling_Tool/Core/Slope_Tool.py
calculate
staticmethod
¶
Compute the slope using the specified method (static method).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
method
|
str
|
Computation method; one of 'sklearn', 'scipy', 'numpy', 'manual' |
'sklearn'
|
Returns:
| Type | Description |
|---|---|
float or tuple
|
Slope value (scipy returns a tuple; the other methods return a float) |
Examples:
>>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
>>> SlopeCalculator.calculate(df, 'values', method='numpy')
1.0
Source code in Modeling_Tool/Core/Slope_Tool.py
calculate_slope_sklearn
¶
Compute the slope of a data column using scikit-learn's LinearRegression.
Based on ordinary least squares: fit the data points with a LinearRegression model and return the slope coefficient of the linear regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
Examples:
Source code in Modeling_Tool/Core/Slope_Tool.py
calculate_slope_scipy
¶
Compute the slope of a data column using SciPy's linregress function.
Based on ordinary least squares: fit the data points with scipy.stats.linregress and return the slope along with additional statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple (slope, r_value, p_value, std_err) containing: - slope: slope value - r_value: correlation coefficient - p_value: p-value - std_err: standard error |
Examples:
>>> df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
>>> slope, r, p, se = calculate_slope_scipy(df, 'values')
>>> print(f"Slope: {slope}, correlation: {r}")
Slope: 1.0, correlation: 1.0
Source code in Modeling_Tool/Core/Slope_Tool.py
calculate_slope_numpy
¶
Compute the slope of a data column using NumPy's polyfit function.
Fit a first-degree polynomial with numpy.polyfit and return the slope of the linear regression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
Examples:
Source code in Modeling_Tool/Core/Slope_Tool.py
calculate_slope_manual
¶
Compute the slope of a data column manually with ordinary least squares.
Implement the least-squares formula by hand to compute the slope of the linear regression: slope = Σ((x - x_mean) * (y - y_mean)) / Σ((x - x_mean)²)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the data |
required |
column
|
str
|
Name of the data column |
required |
Returns:
| Type | Description |
|---|---|
float
|
Slope of the linear regression |
Examples:
Source code in Modeling_Tool/Core/Slope_Tool.py
General Utilities: utils¶
utils
¶
DataFrameProcessor
¶
Utility class for processing DataFrames.
Provide a unified interface for DataFrame operations, including column operations, row filtering and type conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
The DataFrame to process. |
required |
Examples:
>>> processor = DataFrameProcessor(df)
>>> processor.move_column('col_a', 0)
>>> processor.convert_colnames('lower')
Source code in Modeling_Tool/Core/utils.py
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 | |
move_column
¶
Move a column to a given position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
Name of the column to move. |
required |
idx
|
int
|
Target position (0-based) of the column, with |
required |
return_kDF
|
bool
|
Whether to return a kDataFrame. Ignored (treated as False) when |
True
|
h2o_frame
|
bool
|
Whether the input is an H2OFrame. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
The data of the processor with the columns reordered (see the module-level |
Source code in Modeling_Tool/Core/utils.py
convert_colnames
¶
Convert the case of the column names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
how
|
str
|
Conversion method: one of 'lower'/'lowercase', 'upper'/'uppercase', 'cap'/'capitalize'. |
"lowercase"
|
return_kDF
|
bool
|
Whether to return a kDataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
The data with the converted column names. The columns of the processor's own |
Source code in Modeling_Tool/Core/utils.py
col_filter_regex
¶
Filter the columns by a regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
regex
|
str
|
Regular expression. |
required |
case_sensitive
|
bool
|
Whether matching is case-sensitive (ignored when |
True
|
h2o_frame
|
bool
|
Whether the input is an H2OFrame. |
False
|
return_kDF
|
bool
|
Whether to return a kDataFrame. Ignored (treated as False) when |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
|
Source code in Modeling_Tool/Core/utils.py
row_filter_regex
¶
Filter the rows by a regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Name of the column to filter on. |
required |
regex
|
str
|
Regular expression. |
required |
case_sensitive
|
bool
|
Whether matching is case-sensitive. |
True
|
as_index
|
bool
|
Whether to use the filter column as the index. Only honored when |
False
|
return_kDF
|
bool
|
Whether to return a kDataFrame. When True, |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
|
Source code in Modeling_Tool/Core/utils.py
get_dtypes
¶
Get the data types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputFile
|
str
|
Output file path. If given, the table is also written there as CSV, without the index and without a header row. |
None
|
ck_format
|
bool
|
Reserved for a ClickHouse dtype mapping that SMF does not ship: |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The column names and data types (see |
Source code in Modeling_Tool/Core/utils.py
drop_tmp_cols
¶
Drop temporary columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drop_list
|
list
|
List of columns to drop. Names that are not columns of the data are ignored. |
['py_inserttime']
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Source code in Modeling_Tool/Core/utils.py
to_bool_str
¶
FilePathManager
¶
Utility class for managing file paths.
Provide path operations, file listing and directory creation.
Attributes:
| Name | Type | Description |
|---|---|---|
base_path |
str
|
Base path given to the constructor (the current working directory when none is given). It is only stored: none of the methods uses it. |
Examples:
>>> fpm = FilePathManager('/base/path')
>>> fpm.get_filenames('/base/path', '.*\.csv')
>>> fpm.mkdir('output')
Source code in Modeling_Tool/Core/utils.py
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 | |
get_filenames
¶
Get the list of matching file names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Directory path. |
required |
regex
|
str
|
Regular expression. |
required |
Returns:
| Type | Description |
|---|---|
list
|
The matching file names, searched recursively (see the module-level |
Source code in Modeling_Tool/Core/utils.py
add_suffix
¶
Add a suffix to a file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
File path. |
required |
suffix
|
str
|
Suffix. |
"_cut"
|
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in Modeling_Tool/Core/utils.py
mkdir
¶
Create a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_path
|
str
|
Directory path. |
required |
replace
|
bool
|
Whether to replace an existing directory. An existing directory is not deleted or emptied (see the module-level
|
False
|
Returns:
| Type | Description |
|---|---|
int
|
Status code: 0 means success, 1 means the directory already exists ( |
Source code in Modeling_Tool/Core/utils.py
get_curr_abs_path
¶
Get the absolute path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative path, resolved against the directory of the module |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
Source code in Modeling_Tool/Core/utils.py
DateTimeUtils
¶
Utility class for dates and times.
Provide convenient date- and time-related methods.
Examples:
>>> dt_utils = DateTimeUtils()
>>> dt_utils.get_curr_datetime('-')
'20250330-143624'
>>> dt_utils.get_last_vintage()
'202502'
Source code in Modeling_Tool/Core/utils.py
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 | |
get_curr_datetime
¶
Get the current date and time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sep
|
str
|
Separator. |
''
|
Returns:
| Type | Description |
|---|---|
str
|
|
get_buffer_date
¶
Get the buffer date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str
|
Start date. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
get_quarter
¶
Get the quarter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strDate
|
str
|
Date string. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
get_last_vintage
¶
last_month_vintage
¶
Get the vintage of the previous month.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
|
required |
month
|
int
|
|
required |
day
|
int
|
|
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Source code in Modeling_Tool/Core/utils.py
get_valid_vintages
¶
Get the list of valid vintages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sVintage
|
int
|
|
required |
eVintage
|
int
|
|
required |
Returns:
| Type | Description |
|---|---|
list
|
|
Source code in Modeling_Tool/Core/utils.py
WOEIVCalculator
¶
Utility class for computing WOE and IV.
Provide the WOE and IV calculations commonly used in credit scoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the proportions. |
required |
bad_pct_col
|
str
|
Name of the column holding the bad-sample proportion. |
required |
good_pct_col
|
str
|
Name of the column holding the good-sample proportion. |
required |
Examples:
>>> calc = WOEIVCalculator(df, 'bad_pct', 'good_pct')
>>> calc.calc_woe()
>>> calc.calc_iv()
>>> woe, iv = calc.calc_both()
Source code in Modeling_Tool/Core/utils.py
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 | |
calc_woe
¶
Compute the WOE values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fillna
|
bool
|
Passed to |
True
|
Returns:
| Type | Description |
|---|---|
float or Series
|
|
Source code in Modeling_Tool/Core/utils.py
calc_iv
¶
Compute the IV values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fillna
|
bool
|
Passed to |
True
|
Returns:
| Type | Description |
|---|---|
float or Series
|
|
Source code in Modeling_Tool/Core/utils.py
calc_both
¶
Compute the WOE and IV together.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fillna
|
bool
|
Used as both |
True
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in Modeling_Tool/Core/utils.py
bucket_by_cond
¶
bucket_by_cond(df: DataFrame, cond_dict: dict, colname: str, drop_unmatched: bool = True, default=nan) -> DataFrame
Bucket the rows of a DataFrame by a dictionary of query conditions and tag each bucket with its label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Original data. |
required |
cond_dict
|
dict
|
Mapping of |
required |
colname
|
str
|
Name of the new label column. |
required |
drop_unmatched
|
bool
|
If True, drop rows that match no condition (original behavior); if False, keep all rows. |
True
|
default
|
scalar
|
Value assigned to unmatched rows (only used when |
np.nan
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Data with the new label column. |
Notes
The conditions are evaluated with DataFrame.query when drop_unmatched=True and with DataFrame.eval when
drop_unmatched=False; df itself is not modified. A row that satisfies several conditions is treated
differently by the two modes. With drop_unmatched=True it is repeated once for every matching label (it keeps its
original index value, so the index can contain duplicates) and the rows come out grouped by label, in the order of
cond_dict. With drop_unmatched=False every row appears exactly once, in its original order, and carries the
label of the last matching condition. An empty cond_dict raises ValueError when drop_unmatched=True.
Source code in Modeling_Tool/Core/utils.py
cut2pieces
¶
Split a list into several sub-lists.
Split the list into consecutive chunks of len(varlist) // n elements. The elements left over at the end are added
to the last chunk, so that chunk is the longest, and the number of chunks is not always n (see Notes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list
|
List to split. |
required |
n
|
int
|
Number of sub-lists wanted. It sets the chunk size |
4
|
Returns:
| Type | Description |
|---|---|
list
|
The resulting sub-lists, in order (concatenating them gives |
Notes
The number of chunks is ceil(len(varlist) / (len(varlist) // n)) - 1, which is n only for some lengths: 10
items with n=4 give 4 chunks (sizes 2, 2, 2, 4), whereas 8 items with n=4 give only 3 chunks (sizes 2, 2, 4).
The call fails when n is larger than len(varlist) (the chunk size is 0: ValueError) and when that formula
gives fewer than 2 chunks, which is the case for n=1 and for n=2 with an even number of items (IndexError).
Examples:
>>> cut2pieces([1, 2, 3, 4, 5, 6, 7, 8], n=4)
[[1, 2], [3, 4], [5, 6, 7, 8]]
>>> cut2pieces(list(range(1, 11)), n=4)
[[1, 2], [3, 4], [5, 6], [7, 8, 9, 10]]
Source code in Modeling_Tool/Core/utils.py
check_colname_exist
¶
Check whether a column name exists in a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
colname
|
str
|
Column name to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the column name exists, False otherwise. |
Examples:
Source code in Modeling_Tool/Core/utils.py
get_curr_abs_path
¶
Get the absolute path of a path relative to the current module's directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Relative path. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Absolute path string. |
Source code in Modeling_Tool/Core/utils.py
get_curr_datetime
¶
Get the current date and time as a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sep
|
str
|
Separator between the date and the time. |
''
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted date-time string in the format YYYYMMDD{sep}HHMMSS. |
Examples:
>>> get_curr_datetime() # returns something like '20250330143624'
>>> get_curr_datetime('-') # returns something like '20250330-143624'
Source code in Modeling_Tool/Core/utils.py
get_buffer_date
¶
Get the date 4 weeks (28 days) before the start date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_date
|
str
|
Start date in the format 'YYYY-MM-DD'. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Date 4 weeks before the start date, in the format 'YYYY-MM-DD'. |
Examples:
Source code in Modeling_Tool/Core/utils.py
get_quarter
¶
Get the quarter from a date string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strDate
|
str
|
Date string in the format 'YYYYMM' or 'YYYYMMDD'. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Quarter (1-4). |
Examples:
Source code in Modeling_Tool/Core/utils.py
get_last_vintage
¶
Get the year-month string of the previous month.
Returns:
| Type | Description |
|---|---|
str
|
Year-month string of the previous month, in the format 'YYYYMM'. |
Examples:
Source code in Modeling_Tool/Core/utils.py
read_csv
¶
Read a CSV file and return a kDataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the CSV file. |
required |
*args
|
Additional positional arguments passed to pandas.read_csv. |
()
|
|
**kwargs
|
Additional keyword arguments passed to pandas.read_csv. |
{}
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
kDataFrame containing the data. |
Examples:
Source code in Modeling_Tool/Core/utils.py
df_to_h2oframe
¶
Convert a DataFrame to an H2OFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. An object that already is an |
required |
Returns:
| Type | Description |
|---|---|
H2OFrame
|
The H2OFrame object. |
Notes
h2o is imported inside the function and must be installed.
Examples:
Source code in Modeling_Tool/Core/utils.py
move_column
¶
Move the given column to a specific position in a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame (an |
required |
colname
|
str
|
Name of the column to move. |
required |
idx
|
int
|
Target position (0-based) of the column, with |
required |
return_kDF
|
bool
|
Whether to return a kDataFrame. Ignored (treated as False) when |
True
|
h2o_frame
|
bool
|
Whether the input is an H2OFrame. |
False
|
Returns:
| Type | Description |
|---|---|
(DataFrame, kDataFrame or H2OFrame)
|
Data with the columns reordered (a new frame; |
Notes
h2o is imported unconditionally at the start of the function, so the call raises ModuleNotFoundError when h2o
is not installed, even for pandas input.
Examples:
>>> df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]})
>>> move_column(df, 'c', 0) # move column 'c' to the first position
Source code in Modeling_Tool/Core/utils.py
convert_to_vintage
¶
Generate a vintage column from a time column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
vintage_colname
|
str
|
Name of the generated vintage column (a column with this name is overwritten). |
'VINTAGE'
|
by
|
str
|
Name of the time column. The column is cast to string and the first |
'TRAN_TMS'
|
return_kDF
|
bool
|
Whether to return a kDataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
Data with the vintage column added. |
Notes
The vintage column is added to the input data itself (in place), so the caller's frame gains the column as well as
the returned one. The column has pandas string dtype and holds the vintage as YYYYMM text (for example
'202503'); values without a YYYY-MM pattern (other separators, compact dates, missing values) become missing.
Examples:
>>> df = pd.DataFrame({'TRAN_TMS': ['2025-03-15 10:00:00', '2025-03-20 11:00:00']})
>>> convert_to_vintage(df)
Source code in Modeling_Tool/Core/utils.py
col_filter_regex
¶
col_filter_regex(data, regex='.*?of_co_at_12m', case_sensitive=True, h2o_frame=False, return_kDF=True)
Filter the columns of a DataFrame by matching the column names against a regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or H2OFrame
|
Input data. |
required |
regex
|
str
|
Regular expression pattern, searched ( |
".*?of_co_at_12m"
|
case_sensitive
|
bool
|
Whether matching is case-sensitive. Ignored when |
True
|
h2o_frame
|
bool
|
Whether the input is an H2OFrame. If True, |
False
|
return_kDF
|
bool
|
Whether to return a kDataFrame. Ignored (treated as False) when |
True
|
Returns:
| Type | Description |
|---|---|
(DataFrame, kDataFrame or H2OFrame)
|
Filtered data (only the matching columns, in their original order). |
Notes
For pandas input the column names must be strings.
Examples:
>>> df = pd.DataFrame({'score_at_12m': [1, 2], 'other_col': [3, 4]})
>>> col_filter_regex(df, regex='score_at_12m')
Source code in Modeling_Tool/Core/utils.py
row_filter_regex
¶
Filter the rows of a DataFrame by matching one column against a regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
col
|
str
|
Name of the column to filter on. |
required |
regex
|
str
|
Regular expression pattern, searched ( |
required |
case_sensitive
|
bool
|
Whether matching is case-sensitive. |
True
|
as_index
|
bool
|
Whether to use the filter column as the index. It is only honored when |
False
|
return_kDF
|
bool
|
Whether to return a kDataFrame. When True, |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
Filtered data. |
Notes
The values of col are cast to str before matching, so numbers are matched through their text and missing values
through 'nan' or 'None'.
Examples:
>>> df = pd.DataFrame({'name': ['apple', 'banana', 'cherry'], 'value': [1, 2, 3]})
>>> row_filter_regex(df, 'name', 'a.*')
Source code in Modeling_Tool/Core/utils.py
convert_colnames
¶
Convert the column names of a DataFrame to a uniform case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
how
|
str
|
Conversion method. One of 'lower'/'lowercase', 'upper'/'uppercase', 'cap'/'capitalize' (compared case-insensitively). |
"lowercase"
|
return_kDF
|
bool
|
Whether to return a kDataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
Data with the converted column names. |
Notes
The columns of the input data are renamed in place, so the caller's frame changes as well as the returned one. The
column names must be strings. how is not validated: any other value fails with UnboundLocalError.
Examples:
Source code in Modeling_Tool/Core/utils.py
proc_freq
¶
Compute frequencies and percentages, mimicking SAS PROC FREQ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
var
|
str
|
Name of the column to tabulate. |
required |
return_kDF
|
bool
|
Whether to return a kDataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Statistics table with the columns frequency, percent, cumFrequency and cumPercent. It is indexed by the distinct
values of |
Examples:
Source code in Modeling_Tool/Core/utils.py
quantile_rename_map
¶
Map the percentile labels that DataFrame.describe creates ('29%', '2.5%', '50%') to Q<percent>.
The label is read back from its text, so 0.29 gives 'Q29': computing int(0.29 * 100) gave 28 (the product is
28.999999999999996), which never matched the pandas label '29%', and a fractional percent kept the pandas label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
iterable
|
Column labels of a |
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in Modeling_Tool/Core/utils.py
proc_means
¶
Compute descriptive statistics, mimicking SAS PROC MEANS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
varlist
|
list
|
List of columns to summarize; defaults to all columns. |
None
|
quantiles
|
list
|
List of quantiles. |
[0.05, 0.15, 0.25, 0.5, 0.75, 0.95, 0.99]
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Statistics table with one row per summarized column and the upper-case columns |
Notes
Only numeric columns are summarized (the default of DataFrame.describe): non-numeric columns of varlist are
silently left out of the result. Every quantile column is named Q<percent> (0.29 gives Q29, 0.075
gives Q7.5), and the median column, which describe always adds, is Q50.
Examples:
Source code in Modeling_Tool/Core/utils.py
capping_score
¶
Scale model scores and cap them at an upper limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame (an |
required |
pb_score
|
str
|
Name of the score column. |
required |
multiplier
|
float
|
Score scaling multiplier. |
1
|
df_type
|
str
|
Data type, 'DataFrame' or 'h2o' (compared case-insensitively). Any value other than 'h2o' selects the pandas branch. |
'DataFrame'
|
Returns:
| Type | Description |
|---|---|
Series or H2OFrame
|
Processed scores: |
Notes
Known limitation: as implemented, the pandas branch applies the cap with a scalar if on the whole column, so it
raises ValueError ("The truth value of a Series is ambiguous") for any pandas input; only df_type='h2o' works.
Examples:
Source code in Modeling_Tool/Core/utils.py
get_filenames
¶
Get the names of the files under a path that match a regular expression.
The folder is searched recursively, including its sub-folders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Folder path. |
required |
regex
|
str
|
Regular expression pattern, searched ( |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of matching file names, in |
Examples:
Source code in Modeling_Tool/Core/utils.py
sas_to_csv_by_folder
¶
Convert all SAS datasets in a folder to CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_path
|
str
|
Path of the folder containing the SAS files. It must end with a path separator (for example |
required |
Returns:
| Type | Description |
|---|---|
int
|
Execution status code (0 means success). |
Notes
Every file whose name contains sas7bdat is converted with sas_to_csv and written next to the source file, with
sas7bdat replaced by csv in its path. Sub-folders are also searched, but only the file names are kept, so a
file located in a sub-folder is looked up in folder_path and the conversion fails.
Examples:
Source code in Modeling_Tool/Core/utils.py
read_attr_list
¶
Read an attribute list file (one attribute per line).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
File path. |
"pe_attr_list.txt"
|
lower
|
bool
|
Whether to convert the attributes to lower case. With the default False they are returned in upper case. |
False
|
Returns:
| Type | Description |
|---|---|
list
|
List of attributes, one per line of the file, with surrounding whitespace removed and converted to upper case (or
to lower case when |
Examples:
Source code in Modeling_Tool/Core/utils.py
write_attr_list
¶
Write a list of variables to a file.
Each variable is converted with str and written to the file followed by sep, so the file also ends with a
separator. An existing file is overwritten.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_list
|
list
|
List of variables to write. |
required |
path
|
str
|
Output file path. |
"_vls_results.txt"
|
sep
|
str
|
Separator written after every variable, the last one included. The default is the newline character. |
"\n"
|
quote
|
str
|
Quote type: 'double', 'single' or 'none'. Any other value is handled like 'none' (no quotes). |
'double'
|
Returns:
| Type | Description |
|---|---|
None
|
|
Examples:
Source code in Modeling_Tool/Core/utils.py
list_filter_regex
¶
Filter list elements by a regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ls
|
list
|
Input list (of strings). |
required |
regex
|
str
|
Regular expression pattern, searched ( |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of matching elements. |
Examples:
Source code in Modeling_Tool/Core/utils.py
list_to_h2oFrame
¶
Convert a value to an H2O Frame of the given length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val
|
str or float or int
|
Value to repeat. |
required |
length
|
int
|
Length of the frame. |
required |
Returns:
| Type | Description |
|---|---|
H2OFrame
|
H2OFrame containing the repeated value. |
Notes
h2o is imported inside the function and must be installed.
Examples:
Source code in Modeling_Tool/Core/utils.py
odds_score
¶
Compute the odds score from a probability score.
Used to convert a probability into a credit score scale. The score is
score_point - margin_point / ln(2) * (ln(event_ratio) + ln(pb_score / (1 - pb_score))).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pb_score
|
float or array - like
|
Predicted probability of the event, strictly between 0 and 1 (a scalar, a numpy array or a pandas Series). |
required |
event_ratio
|
float
|
Event ratio: the odds of non-event to event at which the score equals |
15
|
margin_point
|
float
|
Score point difference: the points subtracted from the score every time the odds |
20
|
score_point
|
float
|
Base score point. |
500
|
Returns:
| Type | Description |
|---|---|
float or array - like
|
Odds score, of the same kind as |
Examples:
Source code in Modeling_Tool/Core/utils.py
last_Month_Vintage
¶
Get the year-month of the previous month as an integer in the format YYYYMM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
Year. |
required |
month
|
int
|
Month. |
required |
day
|
int
|
Day. It only has to be a valid day of |
required |
Returns:
| Type | Description |
|---|---|
int
|
Previous month of the date |
Examples:
Source code in Modeling_Tool/Core/utils.py
read_sas_file
¶
Read a SAS dataset file.
The SAS file is read with latin-1 encoding, which is the default encoding of SAS Studio and SAS Grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path_name
|
str
|
Path to the SAS file (a |
''
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
kDataFrame containing the data. |
Examples:
Source code in Modeling_Tool/Core/utils.py
sas_to_csv
¶
Convert a SAS dataset to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fileNameWithPath
|
str
|
Path to the input SAS file. |
required |
outputFileNameWithPath
|
str
|
Path to the output CSV file (written without the index column). |
required |
timecounter
|
bool
|
Whether to report the execution time (in minutes) through the logger at INFO level. |
True
|
Returns:
| Type | Description |
|---|---|
int
|
Execution status code (0 means success). |
Examples:
Source code in Modeling_Tool/Core/utils.py
merge_all_data
¶
Merge multiple datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
The DataFrames to merge, passed as positional arguments. They are merged from left to right; at least one is required. |
()
|
|
on
|
str
|
Name of the join key column. It must exist in every DataFrame. |
"APPLICATION_ID"
|
how
|
str
|
Join type: 'left', 'right', 'inner' or 'outer'. |
"left"
|
return_kDF
|
bool
|
Whether to return a kDataFrame. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame or kDataFrame
|
Merged data. |
Notes
In the i-th merge (counting from 0) the non-key columns that exist on both sides get the suffixes _merge{i} (left)
and _merge{i+1} (right). With a single DataFrame nothing is merged and that frame is returned; with no DataFrame
the call fails with IndexError.
Examples:
>>> df1 = pd.DataFrame({'id': [1, 2], 'a': [3, 4]})
>>> df2 = pd.DataFrame({'id': [1, 2], 'b': [5, 6]})
>>> merge_all_data(df1, df2, on='id')
Source code in Modeling_Tool/Core/utils.py
get_valid_vintages
¶
Get the list of valid vintages within the given range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sVintage
|
int
|
Start vintage (format YYYYMM). |
required |
eVintage
|
int
|
End vintage (format YYYYMM). |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of valid vintages: the integers from |
Examples:
Source code in Modeling_Tool/Core/utils.py
set_non_number_str
¶
Import a file as an H2OFrame and set all non-numeric columns to string type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h2o_tbl_path
|
str
|
Path to the file to import (anything accepted by |
required |
Returns:
| Type | Description |
|---|---|
H2OFrame
|
The processed H2OFrame: columns detected as |
Notes
The function calls h2o.init(min_mem_size='100G') (it connects to a running H2O cluster or starts a local one that
asks for at least 100 GB of memory) and imports the file twice: first to detect the column types, then again with the
final types. h2o must be installed.
Examples:
Source code in Modeling_Tool/Core/utils.py
list_to_SQL
¶
Convert a list to a SQL-formatted string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ls
|
list
|
Input list. Without |
required |
excl
|
list
|
List of elements to exclude. |
[]
|
prefix
|
str
|
Column-name prefix (such as a table alias), written before every element as |
''
|
wquote
|
bool
|
Whether to wrap each element in single quotes. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
SQL-formatted string: the elements joined by commas without spaces. |
Notes
With wquote=True the elements are quoted before they are compared with excl, so excl must then contain the
quoted text ("'b'") to exclude anything. The comma after an element depends only on its position in ls, so when
the last element of ls is excluded the result ends with a trailing comma (list_to_SQL(['a', 'b'], excl=['b'])
returns 'a,').
Examples:
Source code in Modeling_Tool/Core/utils.py
bool_to_str
¶
Convert the boolean columns of a DataFrame to string type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Converted data: a copy in which every boolean column holds the strings |
Examples:
Source code in Modeling_Tool/Core/utils.py
get_dtypes_file
¶
Get the data type of each column of a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
outputFile
|
str
|
Output file path. If given, the table is also written there as CSV, without the index and without a header row. |
None
|
ck_format
|
bool
|
Reserved for a ClickHouse dtype mapping that SMF does not ship: |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with the column names (column |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
Notes
Boolean columns are converted to strings first (see bool_to_str), so their type is reported as object.
Examples:
Source code in Modeling_Tool/Core/utils.py
add_path_suffix
¶
Add a suffix to a file path (before the file extension).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
File path, with |
required |
suffix
|
str
|
Suffix to add. |
"_cut"
|
Returns:
| Type | Description |
|---|---|
str
|
File path with the suffix added. |
Notes
The file name is split at its dots and only the first two parts are used, so 'a.tar.gz' becomes 'a_cut.tar'
and a name without a dot fails with IndexError. A bare file name (no /) comes back with a leading /
('file.csv' gives '/file_cut.csv').
Examples:
Source code in Modeling_Tool/Core/utils.py
h2o_apply_regex
¶
Apply a regular-expression transformation function to a column of an H2O Frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
H2OFrame
|
Input data. |
required |
colname
|
str
|
Column name. It must be a string. |
required |
func
|
callable
|
Function to apply to every element of the column. |
required |
Returns:
| Type | Description |
|---|---|
H2OFrame
|
The transformed H2OFrame: a new frame with the single column |
Notes
The column is downloaded as a pandas Series, func is applied there element by element and the result is uploaded
again, so the column must fit in memory. A colname that is not a string fails with UnboundLocalError. h2o
is imported inside the function and must be installed.
Examples:
Source code in Modeling_Tool/Core/utils.py
get_summary_rpt
¶
Merge reports into a feature summary report.
Combine the Means report, the IV/PSI report and the correlation report into one comprehensive report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
means_rpt
|
DataFrame
|
Means statistics report, indexed by variable name (for example the output of |
required |
iv_psi_rpt
|
DataFrame
|
IV/PSI report. It needs a |
required |
corr_rpt
|
DataFrame
|
Correlation report. It needs a |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Merged summary report: the three reports joined on the variable name (an inner join, so a variable missing from any report is dropped), with all column names converted to upper case. |
Examples:
Source code in Modeling_Tool/Core/utils.py
flatten_json_attr
¶
Flatten a column of JSON-format model attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the JSON column. |
required |
jsonColname
|
str
|
Name of the JSON column. Every cell must be a string that |
"data"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The flattened DataFrame: the columns of |
Notes
The cells are parsed with ast.literal_eval, which means Python literal syntax: JSON true, false and
null are not accepted. The column dropped from the output is the one literally named 'data', whatever
jsonColname is, so with another jsonColname the JSON column itself stays in the result. The flattened keys are
joined side by side (pd.concat(axis=1)) with a new 0 to n-1 index, so data should have the default index;
with any other index the rows no longer line up (reset the index first).
Examples:
Source code in Modeling_Tool/Core/utils.py
parse_odps_schema
¶
Parse an ODPS schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema_list
|
list
|
List of ODPS schema entries, one per column. The string form of each entry must look like
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary mapping field names to data types. |
Examples:
>>> parse_odps_schema(['<column col1, type string>', '<column col2, type bigint>'])
{'col1': 'string', 'col2': 'bigint'}
Source code in Modeling_Tool/Core/utils.py
npnan2none
¶
Convert np.nan and np.nat values in a DataFrame to None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Converted data. Columns that contain missing values end up with |
Notes
The object-dtype columns of the input df are reassigned in place before the conversion, so the caller's frame is
modified as well: an object column whose values can all be cast to float (for example numeric strings) is converted to
float.
Examples:
Source code in Modeling_Tool/Core/utils.py
drop_tmp_cols
¶
Drop temporary columns from a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame. |
required |
drop_list
|
list
|
List of temporary columns to drop. Names that are not columns of |
['py_inserttime']
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Data with the temporary columns dropped (a new frame; |
Examples:
Source code in Modeling_Tool/Core/utils.py
mkdir_if_not_exist
¶
Create a directory if it does not exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
folder_path
|
str
|
Folder path. Missing parent folders are created as well. |
required |
replace
|
bool
|
Whether to replace the directory if it already exists. Despite the name, an existing directory is neither deleted
nor emptied: with |
False
|
Returns:
| Type | Description |
|---|---|
int or None
|
Status code: 0 means success, 1 means the directory already exists (and |
Examples:
Source code in Modeling_Tool/Core/utils.py
parse_sql_file
¶
parse_sql_file(sql_path: str = None, sql_query: str = None, split: bool = False, format_select: bool = False, **kwargs)
Parse a SQL file and substitute variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql_path
|
str
|
Path to the SQL file. Exactly one of |
None
|
sql_query
|
str
|
SQL query string. Exactly one of |
None
|
split
|
bool
|
Whether to split multiple queries. |
False
|
format_select
|
bool
|
Whether to automatically format the SELECT fields (one field per line, leading-comma style). |
False
|
**kwargs
|
Variables in the SQL to substitute: every |
{}
|
Returns:
| Type | Description |
|---|---|
str or list
|
Parsed SQL string or list of strings. With |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If neither or both of |
Notes
Comments are removed first (optimizer hints /*+ ... */ are kept). A placeholder without a matching keyword is left
as it is and a UserWarning ("Missing argument(s) ...") is issued.
Examples:
>>> parse_sql_file(sql_path='query.sql', table_name='my_table', date='2025-01-01')
>>> parse_sql_file(sql_path='query.sql', format_select=True, table_name='my_table')
Source code in Modeling_Tool/Core/utils.py
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 | |
calc_woe
¶
Compute the weight of evidence (WOE).
WOE = ln(the bin's share of all bad samples / the bin's share of all good samples)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the proportions. |
required |
bad_pct
|
str
|
Name of the column holding the bad-sample proportion. |
required |
good_pct
|
str
|
Name of the column holding the good-sample proportion. |
required |
fillwoe
|
bool
|
Value returned when |
True
|
Returns:
| Type | Description |
|---|---|
float or Series
|
WOE value(s): a Series aligned with |
Notes
A row in which a proportion is 0 is not filled: a zero bad proportion gives -inf, a zero good proportion gives
inf and two zeros give NaN, whatever fillwoe is.
Examples:
>>> df = pd.DataFrame({'bad_pct': [0.3, 0.5], 'good_pct': [0.7, 0.5]})
>>> calc_woe(df, 'bad_pct', 'good_pct')
Source code in Modeling_Tool/Core/utils.py
calc_iv
¶
Compute the information value (IV).
IV = (the bin's share of all bad samples - the bin's share of all good samples) * WOE
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing the proportions. |
required |
bad_pct
|
str
|
Name of the column holding the bad-sample proportion. |
required |
good_pct
|
str
|
Name of the column holding the good-sample proportion. |
required |
filliv
|
bool
|
Value returned when |
True
|
Returns:
| Type | Description |
|---|---|
float or Series
|
IV value(s): a Series aligned with |
Notes
A row in which one proportion is 0 is not filled: its IV is inf (NaN when both proportions are 0), whatever
filliv is.
Examples:
>>> df = pd.DataFrame({'bad_pct': [0.3, 0.5], 'good_pct': [0.7, 0.5]})
>>> calc_iv(df, 'bad_pct', 'good_pct')
Source code in Modeling_Tool/Core/utils.py
save_model
¶
Save a LightGBM model using pickle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
Model object to save. |
required |
filename
|
str
|
Path to save the model to. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Execution status code (0 means success). |
Notes
The object is written with joblib.dump exactly as given, with no SMF artifact envelope and no metadata, so any
picklable object works, not only LightGBM models. The exported Modeling_Tool.save_model is the metadata-aware
version from Modeling_Tool.Core.Model_Registry_Tool.
Examples:
Source code in Modeling_Tool/Core/utils.py
load_model
¶
Load a pickled model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the model file. |
required |
Returns:
| Type | Description |
|---|---|
object
|
The loaded model object. |
Notes
The file is read with joblib.load and the object is returned exactly as stored: a file written by the
metadata-aware Modeling_Tool.save_model comes back as its artifact dict, not as the model (use
Modeling_Tool.load_model for that). Only load files from a trusted source.
Examples:
Source code in Modeling_Tool/Core/utils.py
scoring
¶
Score data with a model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
model
|
sklearn-like model
|
Machine learning model. It must provide |
required |
varlist
|
list
|
List of feature variables. |
required |
scr_name
|
str
|
Name of the score column (an existing column with this name is overwritten). |
required |
keeplist
|
list
|
List of columns to keep. The score column |
None
|
all_missing_spec_value
|
float
|
Score value to assign to samples in which all features are missing. It is applied only when it is truthy, so |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the scores. |
Notes
data itself is not modified. When some rows have all varlist features missing, those rows are moved behind the
other rows (their index labels are kept), so the row order of the result can differ from data.
Examples:
Source code in Modeling_Tool/Core/utils.py
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 | |
get_missing_indicator
¶
Add Missing Indicator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
subset
|
list of str
|
Names of the columns to check. Required in practice: |
None
|
Returns:
| Type | Description |
|---|---|
Series
|
Integer indicator aligned with |
Notes
The indicator is only returned: no column is added to data.
Source code in Modeling_Tool/Core/utils.py
upload_score
¶
upload_score(data, model, varlist, scr_name, table_name, keeplist=None, retPandas=False, all_missing_spec_value=None)
Upload model scores to MaxCompute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
model
|
sklearn-like model
|
Machine learning model. |
required |
varlist
|
list
|
List of feature variables. |
required |
scr_name
|
str
|
Name of the score column. |
required |
table_name
|
str
|
Name of the target table. |
required |
keeplist
|
list
|
List of columns to keep. The score column |
None
|
retPandas
|
bool
|
Whether to return the pandas DataFrame. |
False
|
all_missing_spec_value
|
float
|
Score value to assign to samples in which all features are missing (see |
None
|
Returns:
| Type | Description |
|---|---|
int or DataFrame
|
Status code (0) or, when |
Notes
The data are scored with scoring, the missing values are converted to None (npnan2none), the temporary
column py_inserttime is dropped (drop_tmp_cols) and the result is uploaded with ODPSRunner.upload_df,
which replaces the table table_name. Creating the ODPSRunner needs the odps extra and the
ALIBABA_CLOUD_ACCESS_KEY_ID / ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
Examples:
Source code in Modeling_Tool/Core/utils.py
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 | |
pull_attributes_in_batch
¶
pull_attributes_in_batch(table_name, varlist, batch_num=6, unikey='flow_id', main_info_select=['*'], add_query='')
Pull Data from DataWorks in Vertical Batch.
The variables are cut into column batches (cut2pieces) and every batch is downloaded with its own query, which
also selects unikey. The remaining columns come from a separate query and all pieces are merged on unikey.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table_name
|
str
|
Name of the source table. |
required |
varlist
|
list of str
|
Names of the attribute columns to pull in vertical batches. At least 6 names are needed (see Notes). |
required |
batch_num
|
int
|
Not used: the number of batches is fixed to 6 inside the function, whatever value is passed. |
6
|
unikey
|
str
|
Name of the unique key column. It is selected in every batch and used to merge the pieces. |
'flow_id'
|
main_info_select
|
list of str
|
Select items of the query that fetches the columns that are not in |
['*']
|
add_query
|
str
|
SQL text appended after the table name in every query (for example a |
''
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The result of the main-info query merged (inner join on |
Notes
It needs an ODPSRunner (the odps extra and the ALIBABA_CLOUD_ACCESS_KEY_ID /
ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables) and downloads with cpu_count() - 1 processes.
varlist is cut with cut2pieces(varlist, 6), which raises ValueError for fewer than 6 names and does not
always return exactly 6 batches.
Source code in Modeling_Tool/Core/utils.py
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 | |
get_feature_names
¶
Get the list of feature names of a model.
Detect the model type automatically and return its feature names. Supports LightGBM, XGBoost, sklearn and other models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
Trained machine learning model object. |
required |
model_type
|
str
|
Model type hint, compared case-insensitively. Allowed values:
Any other string is handled like None. |
None
|
Returns:
| Type | Description |
|---|---|
list
|
List of feature names. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the feature names cannot be obtained. |
Examples:
Source code in Modeling_Tool/Core/utils.py
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 | |
get_feature_names_lgb
¶
Get the feature names of a LightGBM model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LGBMClassifier or LGBMRegressor
|
Trained LightGBM model. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of feature names. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the feature names cannot be obtained. |
Examples:
>>> import lightgbm as lgb
>>> model = lgb.LGBMClassifier().fit(X_train, y_train)
>>> feature_names = get_feature_names_lgb(model)
>>> print(feature_names)
['feature_1', 'feature_2', 'feature_3']
Source code in Modeling_Tool/Core/utils.py
get_feature_names_xgb
¶
Get the feature names of an XGBoost model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
XGBClassifier or XGBRegressor
|
Trained XGBoost model. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of feature names (an empty list when the booster carries no feature names). |
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when the feature names cannot be obtained. |
Examples:
>>> import xgboost as xgb
>>> model = xgb.XGBClassifier().fit(X_train, y_train)
>>> feature_names = get_feature_names_xgb(model)
>>> print(feature_names)
['feature_1', 'feature_2', 'feature_3']
Source code in Modeling_Tool/Core/utils.py
get_feature_names_batch
¶
Get the feature names of multiple models in batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
dict or list
|
Model dictionary {name: model} or list of models. |
required |
model_type
|
str
|
Model type hint (see |
None
|
Returns:
| Type | Description |
|---|---|
dict or list
|
Dictionary or list of feature names, matching the structure of the input. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Examples:
>>> models = {'lgb': lgb_model, 'xgb': xgb_model}
>>> feature_names_dict = get_feature_names_batch(models)
>>> print(feature_names_dict)
{'lgb': ['f1', 'f2'], 'xgb': ['f1', 'f2']}
Source code in Modeling_Tool/Core/utils.py
Encryption: XOR_Encryptor¶
XOR_Encryptor
¶
TextEncryptor
¶
Text encryption and decryption utility class based on the XOR algorithm.
The class encrypts and decrypts single strings and entire pandas DataFrames. Encrypted data is encoded as URL-safe Base64, which makes it easy to store and transmit. This is obfuscation, not strong cryptography: do not rely on it to protect secrets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key used for encryption and decryption. A key is required in practice: with |
None
|
suffix
|
str
|
Suffix that |
'_encrypted'
|
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The key given at construction. |
suffix |
str
|
The column-name suffix given at construction. |
Examples:
>>> encryptor = TextEncryptor(key="my_secret_key")
>>> encrypted = encryptor.encrypt("Hello World")
>>> encryptor.decrypt(encrypted)
'Hello World'
Source code in Modeling_Tool/Core/XOR_Encryptor.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 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 | |
encrypt
¶
Encrypt a string.
The UTF-8 bytes of text are XORed with the repeated key and prefixed with 2 bytes that hold the length of
the plaintext in bytes, which decrypt uses for validation. The result is encoded as URL-safe Base64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Plaintext to encrypt, at most 65,535 bytes of UTF-8. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Encrypted text, URL-safe Base64. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the key is None. |
ZeroDivisionError
|
If the key is an empty string. |
OverflowError
|
If |
Examples:
Source code in Modeling_Tool/Core/XOR_Encryptor.py
decrypt
¶
Decrypt a string produced by encrypt.
The Base64 text is decoded, the first 2 bytes give the stored plaintext length, and the remaining bytes are XORed with the repeated key. The length of the recovered bytes is checked against the stored length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encrypted_text
|
str
|
URL-safe Base64 text produced by |
required |
Returns:
| Type | Description |
|---|---|
str
|
The original plaintext. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If decryption fails for any reason: the input is not valid Base64, the key is wrong or missing, the stored length does not match the recovered length (the data was altered), or the recovered bytes are not valid UTF-8. |
Examples:
>>> encryptor = TextEncryptor(key="secret")
>>> encryptor.decrypt(encryptor.encrypt("Hello"))
'Hello'
Source code in Modeling_Tool/Core/XOR_Encryptor.py
encrypt_dataframe
¶
Encrypt every value of a DataFrame.
All values are converted to strings (a missing value becomes 'nan') and encrypted with encrypt, and the
suffix is appended to every column name. The original DataFrame is not modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
The DataFrame to encrypt. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A new DataFrame of encrypted strings (object dtype) whose column names carry the suffix. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the key is None. |
ZeroDivisionError
|
If the key is an empty string. |
OverflowError
|
If a value, converted to a string, is longer than 65,535 bytes. |
Notes
An encrypted DataFrame cannot be analyzed; decrypt it first. A column name that already contains the suffix text
does not survive a round trip, because decrypt_dataframe removes every occurrence of the suffix.
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
>>> encryptor = TextEncryptor(key="secret")
>>> encryptor.encrypt_dataframe(df).columns.tolist()
['name_encrypted', 'age_encrypted']
Source code in Modeling_Tool/Core/XOR_Encryptor.py
decrypt_dataframe
¶
Decrypt a DataFrame produced by encrypt_dataframe.
Every value is decrypted with decrypt and every occurrence of the suffix is removed from the column names.
The original DataFrame is not modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
A DataFrame produced by |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A new DataFrame whose values are the decrypted strings (object dtype: numbers and missing values come back
as text such as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value cannot be decrypted, for example because the key is wrong or a column was never encrypted. |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [25, 30]})
>>> encryptor = TextEncryptor(key="secret")
>>> decrypted = encryptor.decrypt_dataframe(encryptor.encrypt_dataframe(df))
>>> decrypted.columns.tolist()
['name', 'age']
>>> decrypted['age'].tolist()
['25', '30']
Source code in Modeling_Tool/Core/XOR_Encryptor.py
Extended DataFrame: kDataFrame¶
kDataFrame
¶
kSeries
¶
Bases: Series
The extension class of Pandas Series, paired with kDataFrame: operations on it return kSeries /
kDataFrame objects, and it adds a few scoring and frequency-table helpers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
array-like, Iterable, dict or scalar value
|
The data of the series, exactly as accepted by |
required |
*args
|
tuple
|
Further positional arguments, forwarded unchanged to |
()
|
**kwargs
|
dict
|
Further keyword arguments (for example |
{}
|
Source code in Modeling_Tool/Core/kDataFrame.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
to_pdSeries
¶
Convert kSeries back to pandas Series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
If False, convert a copy of the kSeries. If True, convert the kSeries itself without copying it first, so the returned Series shares its data with this object. The kSeries is never modified or replaced. |
False
|
Returns:
| Type | Description |
|---|---|
Series
|
A plain |
Source code in Modeling_Tool/Core/kDataFrame.py
odds_score
¶
Calculate the odd score based on the given probability score.
Odds Score = (count of sth happening) / (count of sth not happening) Odds Score = pb_score / (1-pb_score) [This ranges from 0 to infinity.] Log Odds Score = np.log(pb_score / (1-pb_score)) [This ranges from -infinity to +infinity] This is helpful for solving binary classification problem. Odds Ratio: The ratio of odds.
The values of the series are used as pb_score, the predicted probability of the event.
Returns:
| Type | Description |
|---|---|
kSeries
|
The scorecard-style score |
Notes
The probabilities are not validated. 0 gives inf, 1 gives -inf, and values outside [0, 1]
or missing values give NaN. For other base score, odds or points-to-double-the-odds settings use
Modeling_Tool.Core.utils.odds_score.
Source code in Modeling_Tool/Core/kDataFrame.py
scale_score
¶
Scale the model scores (for internt segment of MCI model)
Returns:
| Type | Description |
|---|---|
kSeries
|
The values multiplied by 1.112 and capped at 0.9999999 (the index and name of the series are kept). |
Source code in Modeling_Tool/Core/kDataFrame.py
proc_freq
¶
Implement the Python version "proc freq" query in SAS.
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per distinct value of the series (missing values count as a row of their own), indexed by that
value and sorted by decreasing frequency. The columns are |
Source code in Modeling_Tool/Core/kDataFrame.py
kDataFrame
¶
Bases: DataFrame
The extension class of Pandas DataFrame including more useful methods to manipulate dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Any pandas dataframe dataset. Anything accepted by |
required |
*args
|
tuple
|
Further positional arguments, forwarded unchanged to |
()
|
**kwargs
|
dict
|
Further keyword arguments (for example |
{}
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
The extension object of dataframe. |
Attributes:
| Name | Type | Description |
|---|---|---|
added_property |
int, default 1
|
Example of a metadata attribute: it is listed in |
Source code in Modeling_Tool/Core/kDataFrame.py
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 | |
move_column
¶
To move a column into specific place by index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colname
|
str
|
Name of the column to move. It must be a column of the frame. |
required |
idx
|
int
|
Target position (0-based) of the column, with |
required |
inplace
|
bool
|
If False, work on a copy; if True, work on the frame itself. This does not change the result: the
reordered frame is built with |
False
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
A new frame with the same data and the columns reordered. |
Notes
inplace=True is effectively a no-op for the original frame: always use the returned frame.
Source code in Modeling_Tool/Core/kDataFrame.py
convert_to_vintage
¶
To obtain a vintage column by a time/data column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vintage_colname
|
str
|
Name of the column that receives the vintage. A column with this name is overwritten. |
'VINTAGE'
|
by
|
str
|
Name of the date/time column the vintage is taken from. The column is cast to string and the first
|
'TRAN_TMS'
|
inplace
|
bool
|
If True, add the column to the frame itself; if False, add it to a copy and leave the frame unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
The frame holding the new column: the frame itself when |
Notes
Values that contain no YYYY-MM pattern (other separators such as 2024/05/17, compact dates such as
20240517, or missing values) become missing (<NA>) in the vintage column.
Source code in Modeling_Tool/Core/kDataFrame.py
col_filter_regex
¶
To filter the DataFrame columns by regular expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
regex
|
str
|
Regular expression searched ( |
".*?of_co_at_12m"
|
case_sensitive
|
bool
|
If False, the match ignores case. |
True
|
inplace
|
bool
|
If False, work on a copy; if True, work on the frame itself. This does not change the result: the frame the method is called on is never modified in either case. |
False
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
A new frame holding only the matching columns, in their original order (a frame without columns when nothing matches). |
Notes
The column names must be strings, because the pattern is applied through DataFrame.columns.str.
Source code in Modeling_Tool/Core/kDataFrame.py
row_filter_regex
¶
row_filter_regex(col=None, regex: str = None, case_sensitive=True, as_index=False, inplace: bool = False)
To filter the string format row using regex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Name of the column whose values are tested. Required in practice: |
None
|
regex
|
str
|
Regular expression searched ( |
None
|
case_sensitive
|
bool
|
If False, the match ignores case. |
True
|
as_index
|
bool
|
If True, the returned rows are indexed by |
False
|
inplace
|
bool
|
If False, work on a copy; if True, work on the frame itself. This does not change the result: the frame the method is called on is never modified in either case. |
False
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
A new frame with the rows whose value in |
Notes
The values of col are cast to str before matching, so numbers are matched through their text
('1.5') and missing values through 'nan' or 'None'.
Source code in Modeling_Tool/Core/kDataFrame.py
scale_score
¶
Scale the model scores (for internt segment of MCI model)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pb_score
|
str
|
Name of the column that holds the model score (a probability). |
required |
Returns:
| Type | Description |
|---|---|
kSeries
|
The column multiplied by 1.112 and capped at 0.9999999, with the index of the frame. The frame itself is not modified (no column is added). |
Source code in Modeling_Tool/Core/kDataFrame.py
proc_freq
¶
Implement the Python version "proc freq" query in SAS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Name of the column to tabulate. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per distinct value of the column (missing values count as a row of their own), indexed by that
value and sorted by decreasing frequency. The columns are |
Source code in Modeling_Tool/Core/kDataFrame.py
unify_table_col_names
¶
Unify the format of column names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
how
|
str
|
Target format, compared case-insensitively: |
"lowercase"
|
inplace
|
bool
|
If True, rename the columns of the frame itself; if False, work on a copy and leave the frame unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
kDataFrame
|
The frame with the renamed columns: the frame itself when |
Notes
The column names must be strings. how is not validated: any other value fails with
UnboundLocalError. Names that collide after the conversion ('A' and 'a') become duplicate
column names.
Source code in Modeling_Tool/Core/kDataFrame.py
convert_strlist_to_list
¶
cast string-type lists in a specified Series into real lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col
|
str
|
Name of the column that holds the list-like strings, for example |
required |
Returns:
| Type | Description |
|---|---|
kSeries
|
One list of strings per row: the runs of letters, digits and underscores found in |
Notes
The series is rebuilt from the extracted lists, so it has a new default index (0 to n-1) and not the index
of the frame. Any other punctuation also splits a token ('1.5' becomes ['1', '5']), and a missing
value becomes ['nan'] or ['None'].
Source code in Modeling_Tool/Core/kDataFrame.py
to_pdDataFrame
¶
Convert df_extension back to DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inplace
|
bool
|
If False, convert a copy of the kDataFrame. If True, convert the kDataFrame itself without copying it first, so the returned DataFrame shares its data with this object. The kDataFrame is never modified or replaced. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A plain |
Source code in Modeling_Tool/Core/kDataFrame.py
DataFrame and JSON Conversion: Json_Data_Converter¶
Json_Data_Converter
¶
df_to_json
¶
df_to_json(drv_df: DataFrame, input_vars: Optional[List[str]] = None, metadata_cols: Optional[List[str]] = None) -> Dict[str, Any]
Convert a drv_df DataFrame to the JSON format.
Two modes:
- Partitioned mode (input_vars specified):
Metadata columns (the columns that are not in input_vars) are extracted as scalars, and the input_vars
columns are collected into arrays placed under cdc_credit_inputs.
Output: {"":
- Flat mode (input_vars=None):
All columns are placed as arrays at the top level of the JSON, with no distinction between metadata / input_vars.
Output: {"
": [...], " ": [...], ...}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drv_df
|
DataFrame
|
Source DataFrame, one record per row. |
required |
input_vars
|
Optional[List[str]]
|
List of model input feature column names. If None, flat mode is used and every column becomes an array. |
None
|
metadata_cols
|
Optional[List[str]]
|
Metadata columns to specify explicitly in partitioned mode. Ignored in flat mode. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary in JSON format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
In partitioned mode, if the metadata column values are inconsistent. |
KeyError
|
If a column in input_vars does not exist in the DataFrame. |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
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 | |
df_to_json_custom
¶
df_to_json_custom(drv_df: DataFrame, input_vars: List[str], inputs_key: str = 'inputs', metadata_cols: Optional[List[str]] = None, unwrap_single: bool = True) -> Dict[str, Any]
Convert a drv_df DataFrame to the partitioned JSON format, with a custom second-level key and automatic unwrapping.
Similar to the partitioned mode of df_to_json, but: - The key name of the second-level JSON can be customized (via inputs_key) - Arrays of length 1 in the second-level JSON are automatically unwrapped to scalars (via unwrap_single)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drv_df
|
DataFrame
|
Source DataFrame. |
required |
input_vars
|
List[str]
|
Names of the columns placed in the second-level JSON. |
required |
inputs_key
|
str
|
Key name of the second-level JSON; default "inputs". |
'inputs'
|
metadata_cols
|
Optional[List[str]]
|
Top-level metadata columns. If None, they are derived automatically (the columns that are not in input_vars). |
None
|
unwrap_single
|
bool
|
Whether to unwrap arrays of length 1 in the second-level JSON to scalars. Default True. |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
{
"": |
Examples:
>>> df = pd.DataFrame({'req': ['a','a'], 'x': [1,2], 'y': [3,4]})
>>> df_to_json_custom(df, input_vars=['x','y'], inputs_key='features')
{'req': 'a', 'features': {'x': [1,2], 'y': [3,4]}}
>>> df_single = pd.DataFrame({'req': ['a'], 'x': [1], 'y': [3]})
>>> df_to_json_custom(df_single, input_vars=['x','y'], inputs_key='features')
{'req': 'a', 'features': {'x': 1, 'y': 3}}
Source code in Modeling_Tool/Core/Json_Data_Converter.py
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 | |
json_to_df
¶
json_to_df(json_data: Union[str, Dict[str, Any]], input_vars: Optional[List[str]] = None, metadata_cols: Optional[List[str]] = None) -> DataFrame
Restore a DataFrame from the JSON format (the three formats are detected automatically).
Three modes: 1) Row-Oriented mode (the JSON has a cdc_query_credits key) - NEW Top-level scalars are metadata and cdc_query_credits is an array of objects, one row per object. Output: the metadata columns are broadcast to all rows + the object fields are expanded into columns.
{
"requestId": "req@123", "pullLogId": 3836171, ...,
"cdc_query_credits": [
{"_id": "id1", "montoPagar": 922, ...},
{"_id": "id2", "montoPagar": 0, ...}
]
}
2) Partitioned mode (the JSON has a cdc_credit_inputs key) The array columns are taken from cdc_credit_inputs; all other top-level keys are metadata scalars.
{
"requestid": "req_001", "pulllogid": 3836171, ...,
"cdc_credit_inputs": {
"account_open_days": [2381, 4493],
"pagoactual": ["V", "V"]
}
}
3) Flat mode (the JSON has neither cdc_credit_inputs nor cdc_query_credits) All top-level keys are column names; list values are expanded into rows and scalar values are broadcast.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_data
|
Union[str, Dict[str, Any]]
|
JSON string or dictionary. |
required |
input_vars
|
Optional[List[str]]
|
Model input feature column names in partitioned mode. If None, the JSON format is detected automatically. Note: this argument is ignored in row-oriented mode (all fields in cdc_query_credits are expanded). |
None
|
metadata_cols
|
Optional[List[str]]
|
Metadata column names. If None, they are derived automatically (top-level keys other than cdc_*). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The restored DataFrame, with the metadata columns first and the data columns after. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the array lengths are inconsistent, or cdc_query_credits is not an array. |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
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 | |
df_to_json_string
¶
df_to_json_string(drv_df: DataFrame, input_vars: Optional[List[str]] = None, metadata_cols: Optional[List[str]] = None, indent: Optional[int] = 2, ensure_ascii: bool = False) -> str
Convenience wrapper around df_to_json that returns the JSON string directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drv_df
|
DataFrame
|
Source DataFrame, one record per row. |
required |
input_vars
|
Optional[List[str]]
|
List of model input feature column names; None selects the flat mode of |
None
|
metadata_cols
|
Optional[List[str]]
|
Metadata columns to specify explicitly in partitioned mode; ignored in flat mode. |
None
|
indent
|
Optional[int]
|
Number of spaces used to indent the JSON; None gives compact single-line output. |
2
|
ensure_ascii
|
bool
|
Whether to escape non-ASCII characters as \uXXXX. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The JSON text. NaN and infinite values are written as |
Raises:
| Type | Description |
|---|---|
ValueError
|
In partitioned mode, if the metadata column values are inconsistent. |
KeyError
|
If a column in |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
json_string_to_df
¶
json_string_to_df(json_string: str, input_vars: Optional[List[str]] = None, metadata_cols: Optional[List[str]] = None) -> DataFrame
Convenience wrapper around json_to_df that accepts a JSON string as input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_string
|
str
|
JSON text in one of the formats that |
required |
input_vars
|
Optional[List[str]]
|
Model input feature column names; see |
None
|
metadata_cols
|
Optional[List[str]]
|
Metadata column names; see |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The restored table. |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
df_to_json_file
¶
df_to_json_file(drv_df: DataFrame, output_path: str, input_vars: Optional[List[str]] = None, metadata_cols: Optional[List[str]] = None, indent: Optional[int] = 2, ensure_ascii: bool = False) -> str
Convert a drv_df DataFrame to the expected JSON format and write it to a .json file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drv_df
|
DataFrame
|
Source DataFrame, one credit bureau account record per row. |
required |
output_path
|
str
|
Path of the output .json file. |
required |
input_vars
|
Optional[List[str]]
|
List of model input feature column names. With None the flat mode of |
None
|
metadata_cols
|
Optional[List[str]]
|
Metadata column names to specify explicitly (partitioned mode only). If None, they are derived automatically. |
None
|
indent
|
Optional[int]
|
Number of spaces used to indent the JSON. None means compact output (single line). |
2
|
ensure_ascii
|
bool
|
Whether to escape non-ASCII characters as \uXXXX. The default False keeps non-ASCII characters (such as CJK text) as they are. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Absolute path of the written file. |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
load_json_file
¶
Load a .json file into a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path of the .json file. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
The parsed dictionary, whose structure follows the expected JSON format. |
Source code in Modeling_Tool/Core/Json_Data_Converter.py
json_to_file
¶
json_to_file(data: Dict[str, Any], output_path: str, indent: Optional[int] = 2, ensure_ascii: bool = False) -> str
Write a Python dict to a .json file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Dict[str, Any]
|
Dictionary to write. |
required |
output_path
|
str
|
Path of the output .json file. |
required |
indent
|
Optional[int]
|
Number of spaces used to indent the JSON. None means compact single-line output; default 2. |
2
|
ensure_ascii
|
bool
|
Whether to escape non-ASCII characters. Default False. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Absolute path of the written file. |