Example #1
0
def filter_array(lst):
    """
    Filter out NaN values from a list or np.array.

    If the type of the input list implements np.isnan, filter out NaN.
    Otherwise, leave the input list unaltered.

    Example
    -------
    >> L = [1, 2, 3, np.nan]
    >> UtilsContainer.filter_array(L)
    [1, 2, 3]
    >> L = np.array(['a', 'b', 'c', np.nan])
    >> UtilsContainer.filter_array(L)
    ['a', 'b', 'c', np.nan]
    """

    Assert.seq(lst)

    try:
        lst_invalid = np.isnan(lst)
    except TypeError:
        lst_invalid = np.zeros_like(lst, dtype=bool)
    lst_valid = np.logical_not(lst_invalid)

    if isinstance(lst, list):
        result = list(lst[i] for i in range(len(lst_valid)) if lst_valid[i])
    elif isinstance(lst, np.ndarray):
        result = lst[lst_valid]
    else:
        msg = 'Input shall be either list or numpy array, is now a {}'.format(type(lst))
        raise AssertionError(msg)

    assert type(lst) == type(result)
    return result
Example #2
0
def list2dict(lst):
    """
    Convert a list to a dictionary, where the key of each entry are the list
    elements, and the values are indices 0..N, where the ordering is the ordering
    used in the list.
    """

    Assert.seq(lst)

    nr_elements = len(lst)
    result = dict(zip(lst, range(nr_elements)))

    assert isinstance(result, dict), 'Output shall be a dictionary'
    msg = 'All elements of input list ({}) shall be in dictionary ({})'.format(len(result), len(lst))
    assert len(result) == len(lst), msg
    return result