Binning a numpy array

后端 未结 4 623
别跟我提以往
别跟我提以往 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:43

    Just use reshape and then mean(axis=1).

    As the simplest possible example:

    import numpy as np
    
    data = np.array([4,2,5,6,7,5,4,3,5,7])
    
    print data.reshape(-1, 2).mean(axis=1)
    

    More generally, we'd need to do something like this to drop the last bin when it's not an even multiple:

    import numpy as np
    
    width=3
    data = np.array([4,2,5,6,7,5,4,3,5,7])
    
    result = data[:(data.size // width) * width].reshape(-1, width).mean(axis=1)
    
    print result
    

提交回复
热议问题