Binning a numpy array

后端 未结 4 624
别跟我提以往
别跟我提以往 2021-01-04 08:04

I have a numpy array which contains time series data. I want to bin that array into equal partitions of a given length (it is fine to drop the last partition if it is not t

4条回答
  •  长情又很酷
    2021-01-04 08:33

    Since you already have a numpy array, to avoid for loops, you can use reshape and consider the new dimension to be the bin:

    In [33]: data.reshape(2, -1)
    Out[33]: 
    array([[4, 2, 5, 6, 7],
           [5, 4, 3, 5, 7]])
    
    In [34]: data.reshape(2, -1).mean(0)
    Out[34]: array([ 4.5,  3. ,  4. ,  5.5,  7. ])
    

    Actually this will just work if the size of data is divisible by n. I'll edit a fix.

    Looks like Joe Kington has an answer that handles that.

提交回复
热议问题