Python: Frequency of occurrences

前端 未结 3 2093
难免孤独
难免孤独 2021-01-01 18:05

I have list of integers and want to get frequency of each integer. This was discussed here

The problem is that approach I\'m using gives me frequency of floating num

3条回答
  •  清酒与你
    2021-01-01 18:43

    If you don't specify what bins to use, np.histogram and pyplot.hist will use a default setting, which is to use 10 equal bins. The left border of the 1st bin is the smallest value and the right border of the last bin is the largest.

    This is why the bin borders are floating point numbers. You can use the bins keyword arguments to enforce another choice of bins, e.g.:

    plt.hist(data, bins=np.arange(data.min(), data.max()+1))
    

    Edit: the easiest way to shift all bins to the left is probably just to subtract 0.5 from all bin borders:

    plt.hist(data, bins=np.arange(data.min(), data.max()+1)-0.5)
    

    Another way to achieve the same effect (not equivalent if non-integers are present):

    plt.hist(data, bins=np.arange(data.min(), data.max()+1), align='left')
    

提交回复
热议问题