Vectorizing a Numpy slice operation

后端 未结 3 1000
梦如初夏
梦如初夏 2021-01-13 00:53

Say I have a Numpy vector,

A = zeros(100)

and I divide it into subvectors by a list of breakpoints which index into A, for ins

3条回答
  •  感动是毒
    2021-01-13 01:19

    There really isn't a single answer to your question, but several techniques that you can use as building blocks. Another one you may find helpful:

    All numpy ufuncs have a .reduceat method, which you can use to your advantage for some of your calculations:

    >>> a = np.arange(100)
    >>> breaks = np.linspace(0, 100, 11, dtype=np.intp)
    >>> counts = np.diff(breaks)
    >>> counts
    array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
    >>> sums = np.add.reduceat(a, breaks[:-1], dtype=np.float)
    >>> sums
    array([  45.,  145.,  245.,  345.,  445.,  545.,  645.,  745.,  845.,  945.])
    >>> sums / counts  # i.e. the mean
    array([  4.5,  14.5,  24.5,  34.5,  44.5,  54.5,  64.5,  74.5,  84.5,  94.5])
    

提交回复
热议问题