openavmkit.utilities.data
add_sqft_fields
add_sqft_fields(df_in)
Add per-square-foot fields to the DataFrame for land and improvement values.
This function creates new columns based on existing value fields and area fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_in
|
DataFrame
|
Input DataFrame |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with additional per-square-foot-fields |
Source code in openavmkit/utilities/data.py
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 |
|
align_categories
align_categories(df_left, df_right)
Ensure matching categorical dtypes and unified category sets across two DataFrames.
For each column present in either DataFrame, if either side has a pandas Categorical dtype, this function will:
- Convert the other side's column to Categorical (if not already), using the first side's existing categories.
- Compute the union of both categorical sets (preserving order: first df_left's then any new from df_right) and assign this combined set to both DataFrames.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_left
|
DataFrame
|
First DataFrame whose categorical columns will be aligned. |
required |
df_right
|
DataFrame
|
Second DataFrame whose categorical columns will be aligned. |
required |
Returns:
Name | Type | Description |
---|---|---|
left_aligned |
DataFrame
|
Copy of |
right_aligned |
DataFrame
|
Copy of |
Notes
- Columns not of Categorical dtype on either side remain unchanged.
- Missing values are preserved and treated as NaN in the Categorical dtype.
- The original column order and non-categorical columns are unaffected.
Source code in openavmkit/utilities/data.py
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 |
|
calc_spatial_lag
calc_spatial_lag(df_sample, df_univ, value_fields, neighbors=5, exclude_self_in_sample=False)
Compute spatial lag features via Gaussian-weighted averages of nearest neighbors.
Builds a cKDTree on the coordinates in df_sample
and, for each location in
df_univ
, finds its neighbors
nearest points in df_sample
. A spatial lag
is calculated for each field in value_fields
as the weighted mean of the
neighbor values using a Gaussian kernel with bandwidth equal to the mean
neighbor distance (σ) for each prediction point. Missing or zero distances
are handled to avoid division by zero. Optionally excludes the point itself
when computing its own lag.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_sample
|
DataFrame
|
DataFrame of sample points containing at least columns 'latitude',
'longitude', and each field in |
required |
df_univ
|
DataFrame
|
DataFrame of prediction points containing 'latitude' and 'longitude'. May include additional columns; output will append lag columns to this. |
required |
value_fields
|
list of str
|
List of column names in |
required |
neighbors
|
int
|
Number of nearest neighbors to query for each prediction point. Must be
at least 2 to allow exclusion of self when |
5
|
exclude_self_in_sample
|
bool
|
If True, the nearest neighbor at distance zero (self) is excluded from the lag calculation by dropping the first neighbor in the query results. |
False
|
Returns:
Type | Description |
---|---|
DataFrame
|
A copy of |
Raises:
Type | Description |
---|---|
ValueError
|
If |
Notes
- Uses SciPy’s cKDTree for efficient nearest-neighbor lookup.
-
Gaussian kernel weights are computed as:
exp(–(d_ij²) / (2 · σ_i²))
, whered_ij
is the distance from pointi
to neighborj
, andσ_i
is the mean of itsk
neighbor distances. -
Weights are then normalized so that they sum to 1 for each prediction point.
Source code in openavmkit/utilities/data.py
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 |
|
clean_column_names
clean_column_names(df)
Clean the column names in a DataFrame by replacing forbidden characters with legal representations. For one-hot encoded columns (containing '='), ensures clean formatting.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame with cleaned column names |
Source code in openavmkit/utilities/data.py
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 |
|
clean_series
clean_series(series)
Clean the values in a Series by replacing forbidden characters with legal representations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
series
|
Series
|
The series to be cleaned |
required |
Returns:
Type | Description |
---|---|
Series
|
The cleaned series |
Source code in openavmkit/utilities/data.py
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 |
|
combine_dfs
combine_dfs(df1, df2, df2_stomps=False, index='key')
Combine two DataFrames on a given index column.
If df2_stomps
is False, NA values in df1 are filled with values from df2. If
df2_stomps
is True, values in df1 are overwritten by those in df2 for matching keys.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df1
|
DataFrame
|
First DataFrame |
required |
df2
|
DataFrame
|
Second DataFrame |
required |
df2_stomps
|
bool
|
Flag indicating if df2 values should overwrite df1 values (default is False). |
False
|
index
|
str
|
Column name to use as the index for alignment (default is "key"). |
'key'
|
Returns:
Type | Description |
---|---|
DataFrame
|
Combined DataFrame |
Source code in openavmkit/utilities/data.py
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 |
|
count_values_in_common
count_values_in_common(a, b, a_field, b_field=None)
Count all the unique values that two columns of two dataframes have in common
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a
|
DataFrame
|
The first DataFrame |
required |
b
|
DataFrame
|
The second DataFrame |
required |
a_field
|
str
|
The column from the first DataFrame |
required |
b_field
|
str
|
The column from the second DataFrame |
None
|
Returns:
Type | Description |
---|---|
Tuple[int, int]
|
|
Source code in openavmkit/utilities/data.py
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 |
|
df_to_markdown
df_to_markdown(df)
Convert a DataFrame to a markdown-formatted string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
Returns:
Type | Description |
---|---|
str
|
Markdown representation of the DataFrame |
Source code in openavmkit/utilities/data.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
|
div_df_z_safe
div_df_z_safe(df, numerator, denominator)
Perform a divide-by-zero-safe division of two columns in a DataFrame, replacing division by zero with None.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
numerator
|
str
|
Name of the column to use as the numerator |
required |
denominator
|
str
|
Name of the column to use as the numerator/divisor |
required |
Returns:
Type | Description |
---|---|
Series
|
The result of the division with divide-by-zero cases replaced by |
Source code in openavmkit/utilities/data.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 |
|
div_series_z_safe
div_series_z_safe(numerator, denominator)
Perform a divide-by-zero-safe division of two series or arrays, replacing division by zero with None.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
numerator
|
Series | ndarray
|
The series/array that serves as the numerator |
required |
denominator
|
Series | ndarray
|
The series/array that serves as the denominator/divisor |
required |
Returns:
Type | Description |
---|---|
Series | ndarray
|
The result of the division with divide-by-zero cases replaced by |
Source code in openavmkit/utilities/data.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
|
do_per_model_group
do_per_model_group(df_in, settings, func, params, key='key', verbose=False, instructions=None, skip=None)
Apply a function to each subset of the DataFrame grouped by model_group
, updating
rows based on matching indices.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df_in
|
DataFrame
|
Input DataFrame |
required |
settings
|
dict
|
Settings dictionary |
required |
func
|
callable
|
Function to apply to each subset |
required |
params
|
dict
|
Additional parameters for the function |
required |
key
|
str
|
Column name to use as the index for alignment (default is "key") |
'key'
|
verbose
|
bool
|
Whether to print verbose output. Default is False. |
False
|
instructions
|
Any
|
Special instructions for the function |
None
|
skip
|
list
|
List of model group names to skip |
None
|
Returns:
Type | Description |
---|---|
DataFrame
|
Modified DataFrame with updates from the function. |
Source code in openavmkit/utilities/data.py
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 |
|
ensure_categories
ensure_categories(df, df_other, field)
Harmonize categorical levels between two DataFrames for a specified column.
If both df[field]
and df_other[field]
are of pandas Categorical dtype,
this routine computes the union of their categories (preserving the order
from df[field]
first, then any additional categories from
df_other[field]
) and sets both Series to use the combined category list.
If either column is not categorical, the DataFrames are returned unchanged.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Primary DataFrame containing the categorical column to standardize. |
required |
df_other
|
DataFrame
|
Secondary DataFrame whose categorical column will be aligned to the same category set. |
required |
field
|
str
|
Name of the column in both DataFrames to synchronize categories on. |
required |
Returns:
Type | Description |
---|---|
tuple of pandas.DataFrame
|
A 2-tuple |
Source code in openavmkit/utilities/data.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 |
|
load_model_results
load_model_results(model_group, model_name, subset='universe', model_type='main')
Load model prediction results for a specified subset from disk, if available.
The function searches for prediction files under
out/models/{model_group}/{model_type}/{model_name}
in two formats:
-
Parquet: Looks for either
pred_{subset}.parquet
orpred_{model_name}_{subset}.parquet
. If found, reads the file, renames columnkey_x
tokey
(if present), and returns a DataFrame with columns['key', 'prediction']
. -
Pickle: If no parquet is found, checks for
pred_{subset}.pkl
. Loads the pickled object (expected to have attributesdf_universe
,df_sales
, anddf_test
), selects the DataFrame matchingsubset
, and returns its['key', 'prediction']
columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_group
|
str
|
Top-level folder grouping for the model outputs (e.g., experiment or category name). |
required |
model_name
|
str
|
Subfolder name identifying the specific model within the group. |
required |
subset
|
str
|
Which dataset predictions to load. Must be one of:
- |
"universe"
|
model_type
|
str
|
Subdirectory under |
"main"
|
Returns:
Type | Description |
---|---|
DataFrame or None
|
|
Source code in openavmkit/utilities/data.py
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 |
|
merge_and_stomp_dfs
merge_and_stomp_dfs(df1, df2, df2_stomps=False, on='key', how='left')
Merge two DataFrames and resolve overlapping columns by 'stomping'.
Performs a pandas merge of df1
and df2
on key(s) on
, using suffixes
'_1' and '_2' for overlapping column names. After merging, for each
common column (excluding join keys) the function selects values from
df2
wherever non-null if df2_stomps=True
, otherwise prefers df1
's
non-null values. Intermediate suffixed columns are dropped before
returning the final DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df1
|
DataFrame
|
Base DataFrame whose values are used when |
required |
df2
|
DataFrame
|
Secondary DataFrame whose values may overwrite those in |
required |
df2_stomps
|
bool
|
If True, prefer non-null values from |
False
|
on
|
str or list of str
|
Column name or list of column names to join on. |
'key'
|
how
|
str
|
Type of join to perform: 'left', 'right', 'inner', or 'outer'. |
'left'
|
Returns:
Type | Description |
---|---|
DataFrame
|
The merged DataFrame with overlapping columns resolved according to the
|
Source code in openavmkit/utilities/data.py
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 |
|
rename_dict
rename_dict(dict, renames)
Rename the keys of a dictionary according to a given rename map.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dict
|
Dictionary
|
Original dictionary. |
required |
renames
|
Dictionary
|
Diciontary mapping old keys to new keys. |
required |
Returns:
Type | Description |
---|---|
New dictionary with keys renamed
|
|
Source code in openavmkit/utilities/data.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
|