|
28 | 28 |
|
29 | 29 | # * use larray "utils" in LIAM2 (to avoid duplicated code)
|
30 | 30 |
|
31 |
| -from collections import Iterable, Sequence, OrderedDict, abc |
| 31 | +from collections import Iterable, Sequence, OrderedDict |
32 | 32 | from itertools import product, chain, groupby, islice, repeat
|
33 | 33 | import os
|
34 | 34 | import sys
|
@@ -7978,6 +7978,57 @@ def apply(self, transform, *args, **kwargs):
|
7978 | 7978 | # transpose back axis where it was
|
7979 | 7979 | return res_arr.transpose(self.axes & res_arr.axes)
|
7980 | 7980 |
|
| 7981 | + def apply_map(self, mapping, dtype=None): |
| 7982 | + r""" |
| 7983 | + Apply a transformation mapping to array elements. |
| 7984 | +
|
| 7985 | + Parameters |
| 7986 | + ---------- |
| 7987 | + mapping : mapping (dict) |
| 7988 | + Mapping to apply to values of the array. |
| 7989 | + A mapping (dict) must have the values to transform as keys and the new values as values, that is: |
| 7990 | + {<oldvalue1>: <newvalue1>, <oldvalue2>: <newvalue2>, ...}. |
| 7991 | + dtype : type, optional |
| 7992 | + Output dtype. Defaults to None (inspect all output values to infer it automatically). |
| 7993 | +
|
| 7994 | + Returns |
| 7995 | + ------- |
| 7996 | + LArray |
| 7997 | + Axes will be the same as the original array axes. |
| 7998 | +
|
| 7999 | + Notes |
| 8000 | + ----- |
| 8001 | + To apply a transformation given as an LArray (with current values as labels on one axis of |
| 8002 | + the array and desired values as the array values), you can use: ``mapping_arr[original_arr]``. |
| 8003 | +
|
| 8004 | + Examples |
| 8005 | + -------- |
| 8006 | + First let us define a test array |
| 8007 | +
|
| 8008 | + >>> arr = LArray([[0, 2, 1], |
| 8009 | + ... [3, 1, 5]], 'a=a0,a1;b=b0..b2') |
| 8010 | + >>> arr |
| 8011 | + a\b b0 b1 b2 |
| 8012 | + a0 0 2 1 |
| 8013 | + a1 3 1 5 |
| 8014 | +
|
| 8015 | + Now, assuming for a moment that the values of our test array above were in fact some numeric representation of |
| 8016 | + names and we had the correspondence to the actual names stored in a dictionary: |
| 8017 | +
|
| 8018 | + >>> code_to_names = {0: 'foo', 1: 'bar', 2: 'baz', |
| 8019 | + ... 3: 'boo', 4: 'far', 5: 'faz'} |
| 8020 | +
|
| 8021 | + We could get back an array with the actual names by using: |
| 8022 | +
|
| 8023 | + >>> arr.apply_map(code_to_names) |
| 8024 | + a\b b0 b1 b2 |
| 8025 | + a0 foo baz bar |
| 8026 | + a1 boo bar faz |
| 8027 | + """ |
| 8028 | + def transform(v): |
| 8029 | + return mapping.get(v, v) |
| 8030 | + return self.apply(transform, dtype=dtype) |
| 8031 | + |
7981 | 8032 |
|
7982 | 8033 | def larray_equal(a1, a2):
|
7983 | 8034 | import warnings
|
|
0 commit comments