Git Product home page Git Product logo

Comments (5)

saninstein avatar saninstein commented on September 15, 2024

Hi @PedroLacerdaELTE
I will review your suggestion and look what we could do.
Thank you!

from numpy_ext.

miko1ann avatar miko1ann commented on September 15, 2024

Hi, All! I've got same issue.
May be solution could be something like this:

`
def prepend_na(array: np.ndarray, n: int) -> np.ndarray:
"""
Return a copy of array with nans inserted at the beginning.

Parameters
----------
array : np.ndarray
    Input array.
n : int
    Number of elements to insert.

Returns
-------
np.ndarray
    New array with nans added at the beginning.

Examples
--------
>>> prepend_na(np.array([1, 2]), 2)
array([nan, nan,  1.,  2.])
"""

if len(array.shape) == 1:
    return np.hstack(
    (
        nans(n),
        array
    ))
else:
    return np.vstack(
        (
            nans((n, array.shape[1]), array[0].dtype),
            array
        )

)
`

Test:
`
prepend_na(np.ones(4), 2)

array([nan, nan, 1., 1., 1., 1.]

prepend_na(np.ones(4), 20)

array([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,
nan, nan, nan, nan, nan, nan, nan, 1., 1., 1., 1.])

prepend_na(np.ones((4,2)), 2)

array([[nan, nan],
[nan, nan],
[ 1., 1.],
[ 1., 1.],
[ 1., 1.],
[ 1., 1.]]),

prepend_na(np.ones((4,3)), 2)

array([[nan, nan, nan],
[nan, nan, nan],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])

prepend_na(np.ones((4,4)), 2)

array([[nan, nan, nan, nan],
[nan, nan, nan, nan],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]]),

prepend_na(np.ones((4,1)), 2)

array([[nan],
[nan],
[ 1.],
[ 1.],
[ 1.],
[ 1.]])

`

from numpy_ext.

miko1ann avatar miko1ann commented on September 15, 2024

And

def rolling_apply(func: Callable, window: int, *arrays: np.ndarray, n_jobs: int = 1, **kwargs) -> np.ndarray:
    """
    Roll a fixed-width window over an array or a group of arrays, producing slices.
    Apply a function to each slice / group of slices, transforming them into a value.
    Perform computations in parallel, optionally.
    Return a new np.ndarray with the resulting values.

    Parameters
    ----------
    func : Callable
        The function to apply to each slice or a group of slices.
    window : int
        Window size.
    *arrays : list
        List of input arrays.
    n_jobs : int, optional
        Parallel tasks count for joblib. If 1, joblib won't be used. Default is 1.
    **kwargs : dict
        Input parameters (passed to func, must be named).

    Returns
    -------
    np.ndarray

    Examples
    --------
    >>> arr = np.array([1, 2, 3, 4, 5])
    >>> rolling_apply(sum, 2, arr)
    array([nan,  3.,  5.,  7.,  9.])
    >>> arr2 = np.array([1.5, 2.5, 3.5, 4.5, 5.5])
    >>> func = lambda a1, a2, k: (sum(a1) + max(a2)) * k
    >>> rolling_apply(func, 2, arr, arr2, k=-1)
    array([  nan,  -5.5,  -8.5, -11.5, -14.5])
    """
    if not any(isinstance(window, t) for t in [int, np.integer]):
        raise TypeError(f'Wrong window type ({type(window)}) int expected')

    window = int(window)

    if max(len(x.shape) for x in arrays) != 1:
        raise ValueError('Wrong array shape. Supported only 1D arrays')

    if len({array.size for array in arrays}) != 1:
        raise ValueError('Arrays must be the same length')

    def _apply_func_to_arrays(idxs):
        return func(*[array[idxs[0]:idxs[-1] + 1] for array in arrays], **kwargs)

    array = arrays[0]
    rolls = rolling(
        array if len(arrays) == n_jobs == 1 else np.arange(len(array)),
        window=window,
        skip_na=True
    )

    if n_jobs == 1:
        if len(arrays) == 1:
            arr = list(map(partial(func, **kwargs), rolls))
        else:
            arr = list(map(_apply_func_to_arrays, rolls))
    else:
        f = delayed(_apply_func_to_arrays)
        arr = Parallel(n_jobs=n_jobs)(f(idxs[[0, -1]]) for idxs in rolls)

    arr = np.array(arr)  # <- here 
    return prepend_na(arr, n=window - 1)   

from numpy_ext.

emiliobasualdo avatar emiliobasualdo commented on September 15, 2024

I had the same problem
#16 This pull request would solve it

from numpy_ext.

saninstein avatar saninstein commented on September 15, 2024

Version 0.9.8 brings a support of the funcs with multiple output for the rolling_apply

@emiliobasualdo @PedroLacerdaELTE @miko1ann
Thank you for your contribution. Also, please, take my apologies for waiting!

from numpy_ext.

Related Issues (7)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.