Howto bin series of float values into histogram in Python?

前端 未结 3 682
梦谈多话
梦谈多话 2020-12-30 08:40

I have set of value in float (always less than 0). Which I want to bin into histogram, i,e. each bar in histogram contain range of value [0,0.150)

The data I have lo

3条回答
  •  一向
    一向 (楼主)
    2020-12-30 09:04

    When possible, don't reinvent the wheel. NumPy has everything you need:

    #!/usr/bin/env python
    import numpy as np
    
    a = np.fromfile(open('file', 'r'), sep='\n')
    # [ 0.     0.005  0.124  0.     0.004  0.     0.111  0.112]
    
    # You can set arbitrary bin edges:
    bins = [0, 0.150]
    hist, bin_edges = np.histogram(a, bins=bins)
    # hist: [8]
    # bin_edges: [ 0.    0.15]
    
    # Or, if bin is an integer, you can set the number of bins:
    bins = 4
    hist, bin_edges = np.histogram(a, bins=bins)
    # hist: [5 0 0 3]
    # bin_edges: [ 0.     0.031  0.062  0.093  0.124]
    

提交回复
热议问题