Python Forum
modify code to accept 3d array
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
modify code to accept 3d array
#1
import xarray as xr
import numpy as np
def get_grps(s, thresh=-1, Nmin=2):
    """
    Nmin : int > 0
        Min number of consecutive values below threshold.
    """
    s = pd.Series(s)
    m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
    if Nmin > 1:
        m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin-1).fillna(False)
    else:
        m = pd.Series(m, index=s.index)

    # Form consecutive groups
    gps = m.ne(m.shift(1)).cumsum().where(m)

    # Return None if no groups, else the aggregations
    if gps.isnull().all():
        return [0]
    else:
        d = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)

        data = len((d['sum']))  ### returning frequency

        data = np.array(data)



        return (data)

### create some dummy data::

spi = xr.DataArray(dims=("time", "lon", "lat"), data=np.random.randn(324, 180, 360))

### Apply xarray rolling window function::

spi.rolling(time=59).reduce(get_grps)
## then I get this error::

Error:
Traceback (most recent call last): ...... raise Exception("Data must be 1-dimensional") Exception: Data must be 1-dimensional
How can I modify this function to accept 3D data and then apply xarray rolling window properly
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to modify video using pixel array or shader? jhovarie 1 2,732 May-26-2019, 10:52 AM
Last Post: heiner55
  Python/Numpy have I already written the swiftest code for large array? justforkicks1 1 2,808 Dec-12-2017, 11:56 PM
Last Post: squenson

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020