Divide a list into multiple lists based on a bin size

前端 未结 6 583
悲哀的现实
悲哀的现实 2021-01-18 03:02

I have a list containing more than 100,000 values in it.

I need to divide the list into multiple smaller lists based on a specific bin width say 0.1. Can anyone hel

6条回答
  •  旧时难觅i
    2021-01-18 03:13

    Here is a simple and nice way using numpys digitize:

    >>> import numpy as np
    >>> mylist = np.array([-0.234, -0.04325, -0.43134, -0.315, -0.6322, -0.245,
                           -0.5325, -0.6341, -0.5214, -0.531, -0.124, -0.0252])
    >>> bins = np.arange(0,-1,-0.1)
    >>> for i in xrange(1,10):
    ...     mylist[np.digitize(mylist,bins)==i]
    ... 
    array([-0.04325, -0.0252 ])
    array([-0.124])
    array([-0.234, -0.245])
    array([-0.315])
    array([-0.43134])
    array([-0.5325, -0.5214, -0.531 ])
    array([-0.6322, -0.6341])
    array([], dtype=float64)
    array([], dtype=float64)
    

    digitize, returns an array with the index value for the bin that each element falls into.

提交回复
热议问题