np_utils¶
NumPy utility functions for array manipulation and analysis.
This module provides a collection of NumPy-related utility functions including: - Array splitting and grouping - NaN filling and interpolation - Data type inference and conversion - Statistical functions (softmax, normalization, moving average) - Array sampling (categorical, one-hot encoding) - Array transformation (rolling window, shifting) - Polynomial fitting - Ring buffer implementation
RingBuffer
¶
Fixed-capacity ring buffer for efficient append/extend operations.
Supports multi-dimensional elements and provides zero-copy iteration via iter_views() and iter_indices().
Example
import numpy as np
rb = np_utils.RingBuffer(3, np.float32, ())
for x in [1, 2, 3, 4, 5]:
rb.append(x)
rb.to_numpy() # [3.0, 4.0, 5.0]: the last 3 values, in arrival order.
Source code in py_misc_utils/np_utils.py
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 | |
shape
property
¶
Return shape of the buffer contents: (len,) + vshape.
resize(capacity)
¶
Resize the buffer, preserving recent elements if possible.
The raw storage is resized with np.resize(), so growing the buffer may break the chronological order of the preserved elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capacity
|
New capacity. |
required |
Source code in py_misc_utils/np_utils.py
641 642 643 644 645 646 647 648 649 650 651 652 | |
select(indices)
¶
Keep only elements at specified indices.
Indices beyond the current element count are silently dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Array of indices to keep (relative to current buffer). |
required |
Source code in py_misc_utils/np_utils.py
654 655 656 657 658 659 660 661 662 663 664 | |
append(v)
¶
Append a single element to the buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Element to append (must match dtype and vshape). |
required |
Source code in py_misc_utils/np_utils.py
666 667 668 669 670 671 672 673 | |
extend(v)
¶
Extend the buffer with multiple elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Array-like of elements to append. |
required |
Example
import numpy as np
rb = np_utils.RingBuffer(4, np.float64, (2,))
rb.extend(np.array([[1, 2], [3, 4], [5, 6]]))
rb.to_numpy() # [[1, 2], [3, 4], [5, 6]]
Source code in py_misc_utils/np_utils.py
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 | |
to_numpy()
¶
Get all buffer contents as a single contiguous array.
Returns:
| Type | Description |
|---|---|
|
Array of shape (len,) + vshape with elements in chronological order. |
Source code in py_misc_utils/np_utils.py
703 704 705 706 707 708 709 | |
data(dtype=None)
¶
Get buffer contents as a new array (copy).
Unlike to_numpy(), the copy keeps the internal (non-chronological) storage order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
Optional dtype for the returned array. |
None
|
Returns:
| Type | Description |
|---|---|
|
Array of shape (len,) + vshape. |
Source code in py_misc_utils/np_utils.py
711 712 713 714 715 716 717 718 719 720 721 722 723 | |
iter_views()
¶
Iterate over contiguous views of the buffer contents.
Yields:
| Type | Description |
|---|---|
|
Views of the internal buffer in chronological order. |
|
|
Yields 1 or 2 views depending on wrap-around. |
Source code in py_misc_utils/np_utils.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 | |
iter_indices()
¶
Get indices of valid elements in the internal buffer.
Returns:
| Type | Description |
|---|---|
|
Array of indices mapping chronological order to internal storage: |
|
|
data[iter_indices()[i]] is the i-th oldest element. |
Example
import numpy as np
rb = np_utils.RingBuffer(3, np.float32, ())
for x in [1, 2, 3, 4, 5]:
rb.append(x)
rb.iter_indices() # [2, 0, 1]
Source code in py_misc_utils/np_utils.py
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 | |
diff_split(data, mask_fn, sort=True)
¶
Split an array into groups based on a mask function applied to differences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Input array to split. |
required | |
mask_fn
|
Function taking the diff array and returning a boolean mask. |
required | |
sort
|
Whether to sort the data before splitting (default: True). |
True
|
Returns:
| Type | Description |
|---|---|
|
List of index arrays for each group. Use data[result[i]] to fetch split data. |
Example
import numpy as np
data = np.array([1, 100, 2, 200, 3])
groups = np_utils.diff_split(data, lambda x: np.abs(x) > 10)
# Groups in sorted order: [data[g] for g in groups] -> [[1, 2, 3], [100], [200]]
Source code in py_misc_utils/np_utils.py
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 | |
group_splits(data, mask_fn)
¶
Find split indices in an array based on a mask function applied to differences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Input array. |
required | |
mask_fn
|
Function taking the diff array and returning a boolean mask. |
required |
Returns:
| Type | Description |
|---|---|
|
Array of indices where splits should occur. |
Example
import numpy as np
np_utils.group_splits(np.array([1, 5, 6, 30]), lambda x: np.abs(x) > 10)
# [2]: a new group starts after the 6 -> 30 jump.
Source code in py_misc_utils/np_utils.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
group_by_delta(data, mask_fn)
¶
Split an array into groups based on a mask function applied to differences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Input array to split. |
required | |
mask_fn
|
Function taking the diff array and returning a boolean mask. |
required |
Returns:
| Type | Description |
|---|---|
|
List of arrays, each containing a contiguous group. |
Example
import numpy as np
np_utils.group_by_delta(np.array([1, 1, 0, 0, 1]), lambda x: x != 1)
# [array([1]), array([1]), array([0]), array([0, 1])]
Source code in py_misc_utils/np_utils.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
fillna(data, copy=False, defval=0)
¶
Fill NaN entries with a neighbor value.
Each run of NaN entries is filled with the value right after the run, or with the value right before it when the run ends the data, or with defval when the whole data is NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
A numpy array. |
required | |
copy
|
If True, fill a copy of the array, leaving the original unchanged (default: False). |
False
|
|
defval
|
Value used when there is no neighbor to take the value from (default: 0). |
0
|
Returns:
| Type | Description |
|---|---|
|
The array with the NaN entries filled. |
Example
import numpy as np
np_utils.fillna(np.array([1.0, np.nan, 4.0]), copy=True)
# [1.0, 4.0, 4.0]: the run takes the value right after it.
Source code in py_misc_utils/np_utils.py
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 | |
infer_np_dtype(dtypes)
¶
Infer a common NumPy dtype from a sequence of dtypes.
Promotes to the widest type: float64 wins over float32, float32 over integers, and bigger integer types win over smaller ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtypes
|
Sequence of NumPy dtypes. |
required |
Returns:
| Type | Description |
|---|---|
|
Inferred common dtype (default: float32 if no dtypes provided). |
Example
import numpy as np
np_utils.infer_np_dtype([np.int32, np.float32]) # float32
np_utils.infer_np_dtype([]) # float32
Source code in py_misc_utils/np_utils.py
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 | |
maybe_stack_slices(slices, axis=0)
¶
Stack slices into an array if they are numpy arrays.
The list is stacked only when it is non-empty and its first element is an ndarray; note that np.stack() still requires all the elements to have the same shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slices
|
List of arrays or other objects. |
required | |
axis
|
Axis along which to stack (default: 0). |
0
|
Returns:
| Type | Description |
|---|---|
|
Stacked array if all elements are ndarrays, otherwise original list. |
Example
import numpy as np
np_utils.maybe_stack_slices([np.array([1]), np.array([2])]) # array([[1], [2]])
np_utils.maybe_stack_slices([[1], 'x']) # Unchanged: mixed element types.
Source code in py_misc_utils/np_utils.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
to_numpy(data)
¶
Convert various array-like objects to NumPy array.
Handles numpy arrays (returned as-is), pandas DataFrames/Series (via to_numpy), PyTorch tensors (via .numpy()), and other array-likes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Array-like object to convert. |
required |
Returns:
| Type | Description |
|---|---|
|
NumPy ndarray. |
Example
import numpy as np
np_utils.to_numpy([1, 2]) # array([1, 2])
np_utils.to_numpy(np.array([1.5])) # ndarray inputs are returned as-is.
Source code in py_misc_utils/np_utils.py
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 | |
is_numeric(dtype)
¶
Check if a dtype is numeric (integer or floating point).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
NumPy dtype or dtype-like. |
required |
Returns:
| Type | Description |
|---|---|
|
True if dtype is a numeric type. |
Source code in py_misc_utils/np_utils.py
237 238 239 240 241 242 243 244 245 246 | |
is_integer(dtype)
¶
Check if a dtype is integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
NumPy dtype or dtype-like. |
required |
Returns:
| Type | Description |
|---|---|
|
True if dtype is an integer type. |
Source code in py_misc_utils/np_utils.py
249 250 251 252 253 254 255 256 257 258 | |
is_floating(dtype)
¶
Check if a dtype is floating point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
NumPy dtype or dtype-like. |
required |
Returns:
| Type | Description |
|---|---|
|
True if dtype is a floating point type. |
Source code in py_misc_utils/np_utils.py
261 262 263 264 265 266 267 268 269 270 | |
is_numpy(v)
¶
Check if an object is a NumPy array or scalar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Object to check. |
required |
Returns:
| Type | Description |
|---|---|
|
True if object's type is from the numpy module. |
Source code in py_misc_utils/np_utils.py
273 274 275 276 277 278 279 280 281 282 | |
astype(data, col, dtype)
¶
Convert a column of data to a specific dtype if applicable.
A dict dtype only applies to the matching column name, while a plain dtype applies to any numeric column: non-numeric data is always left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Input array. |
required | |
col
|
Column name or index. |
required | |
dtype
|
Target dtype or dict mapping column names to dtypes. |
required |
Returns:
| Type | Description |
|---|---|
|
Data array with column converted if dtype matches, otherwise unchanged. |
Example
import numpy as np
np_utils.astype(np.array([1.5]), 'x', {'x': np.int32}) # array([1])
np_utils.astype(np.array(['a']), 'x', np.int32) # Unchanged (non-numeric).
Source code in py_misc_utils/np_utils.py
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 | |
softmax(x)
¶
Compute softmax along the last axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Input array. |
required |
Returns:
| Type | Description |
|---|---|
|
Softmax probabilities (same shape as input). |
Source code in py_misc_utils/np_utils.py
316 317 318 319 320 321 322 323 324 325 326 327 | |
categorical(un_probs, n=None)
¶
Sample from a categorical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
un_probs
|
Unnormalized probabilities (logits). |
required | |
n
|
Number of samples to draw (default: 1 for 1D, 1 per row for 2D). |
None
|
Returns:
| Type | Description |
|---|---|
|
Sampled indices. Shape: () for 1D with n=None, (n,) for 1D with n>1, |
|
|
or (..., 1) for higher dimensions. |
Example
import numpy as np
np_utils.categorical(np.array([0.2, 0.5, 0.3])) # A single sampled index.
np_utils.categorical(np.array([0.2, 0.5, 0.3]), n=4) # Shape (4,).
Source code in py_misc_utils/np_utils.py
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 | |
onehot(values, num_categories=None)
¶
Convert integer indices to one-hot encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Array of integer indices. |
required | |
num_categories
|
Number of categories (default: max(values) + 1). |
None
|
Returns:
| Type | Description |
|---|---|
|
One-hot encoded array with shape values.shape + (num_categories,). |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any value >= num_categories. |
Example
import numpy as np
np_utils.onehot(np.array([0, 2, 1]))
# [[1, 0, 0], [0, 0, 1], [0, 1, 0]]
Source code in py_misc_utils/np_utils.py
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 | |
normalize(data, axis=None)
¶
Normalize data to zero mean and unit standard deviation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
A numpy array. |
required | |
axis
|
Optional axis the mean and standard deviation are computed along; a None value uses the whole array. |
None
|
Returns:
| Type | Description |
|---|---|
|
The normalized array; zero standard deviations are treated as 1.0 to |
|
|
avoid division by zero. |
Example
import numpy as np
np_utils.normalize(np.array([1.0, 3.0])) # [-1.0, 1.0]
np_utils.normalize(np.array([2.0, 2.0])) # [0.0, 0.0] (zero std).
Source code in py_misc_utils/np_utils.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 | |
hasher(value)
¶
Compute a hash of a numpy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
A numpy array. |
required |
Returns:
| Type | Description |
|---|---|
|
The hash of the array, computed from its dtype, shape and raw bytes. |
Example
import numpy as np
np_utils.hasher(np.array([1, 2])) == np_utils.hasher(np.array([1, 2])) # True
# Different dtype or shape or content -> different hash.
Source code in py_misc_utils/np_utils.py
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | |
moving_average(data, window, include_current=True)
¶
Compute moving average of 1D data.
The array is edge-padded before the convolution, so the output has the same length as the input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
1D input array. |
required | |
window
|
Window size for averaging. |
required | |
include_current
|
If True, average includes current element. If False, average uses previous window elements only (default: True). |
True
|
Returns:
| Type | Description |
|---|---|
|
Moving average array of same length as input. |
Example
import numpy as np
np_utils.moving_average(np.array([1.0, 2.0, 3.0, 4.0]), 2)
# [1.0, 1.5, 2.5, 3.5]
Source code in py_misc_utils/np_utils.py
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 | |
rolling_window(a, window)
¶
Create a rolling window view of the last dimension of an array.
Uses stride tricks for zero-copy windowing: the returned array shares the memory of a, so writing to the result also modifies a.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Input array. |
required | |
window
|
Window size. |
required |
Returns:
| Type | Description |
|---|---|
|
View of array with shape (..., n_windows, window). |
Example
import numpy as np
np_utils.rolling_window(np.array([1, 2, 3, 4]), 2)
# [[1, 2], [2, 3], [3, 4]]
Source code in py_misc_utils/np_utils.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | |
shift(data, pos=1)
¶
Shift array elements along the first axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Input array. |
required | |
pos
|
Number of positions to shift. Positive shifts right (later), negative shifts left (earlier). The vacated entries are filled with the edge values of data. |
1
|
Returns:
| Type | Description |
|---|---|
|
Shifted array of same shape. |
Example
import numpy as np
np_utils.shift(np.array([1, 2, 3, 4]), 2) # [1, 1, 1, 2]
np_utils.shift(np.array([1, 2, 3, 4]), -1) # [2, 3, 4, 4]
Source code in py_misc_utils/np_utils.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 | |
complement_indices(indices, size)
¶
Get complement of indices within a range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Array of indices to exclude. |
required | |
size
|
Total size of the range [0, size). |
required |
Returns:
| Type | Description |
|---|---|
|
Array of indices not in the input indices. |
Example
import numpy as np
np_utils.complement_indices(np.array([1, 3]), 5) # [0, 2, 4]
Source code in py_misc_utils/np_utils.py
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 | |
polyfit_std(yv, xv=None, deg=1)
¶
Fit polynomial and compute standard deviation of residuals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
yv
|
Y values to fit. |
required | |
xv
|
X values (default: 0, 1, 2, ...). |
None
|
|
deg
|
Polynomial degree (default: 1). |
1
|
Returns:
| Type | Description |
|---|---|
|
Tuple of (std_dev, fitted_values, polynomial_object). |
Example
import numpy as np
std, fyv, poly = np_utils.polyfit_std(np.array([0.0, 1.1, 2.0, 3.1]))
# std: residual standard deviation, fyv: fitted y values, poly: Polynomial.
Source code in py_misc_utils/np_utils.py
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 | |
npdict_clone(npd)
¶
Create a deep copy of a dictionary of numpy arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
npd
|
Dictionary mapping keys to numpy arrays. |
required |
Returns:
| Type | Description |
|---|---|
|
New dictionary with copied arrays: modifying a copied array does not |
|
|
affect the original one. |
Source code in py_misc_utils/np_utils.py
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
is_ordered(v, reverse=False)
¶
Check if a sequence is monotonically ordered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Sequence to check. |
required | |
reverse
|
If True, check for non-increasing order. If False, check for non-decreasing order (default: False). |
False
|
Returns:
| Type | Description |
|---|---|
|
True if ordered according to the specified direction. |
Example
np_utils.is_ordered([1, 2, 2, 3]) # True (non-decreasing).
np_utils.is_ordered([3, 2, 1], reverse=True) # True.
np_utils.is_ordered([1, 3, 2]) # False.
Source code in py_misc_utils/np_utils.py
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
array_typecode(dtype)
¶
Get the array typecode for a NumPy dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
NumPy dtype object. |
required |
Returns:
| Type | Description |
|---|---|
|
Array typecode character (e.g., 'f', 'd', 'i', 'l') or None if not found. |
Example
import numpy as np
np_utils.array_typecode(np.dtype(np.float32)) # 'f'
np_utils.array_typecode(np.dtype(np.bool_)) # None
Source code in py_misc_utils/np_utils.py
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 | |