0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

`numpy.histogram`のビンは、最後のビンだけ閉区間になる

Last updated at Posted at 2024-05-06

環境

  • Python 3.12.1
  • numpy 1.26.4

内容

公式ドキュメントに書いてある通りです。

All but the last (righthand-most) bin is half-open

最後のビンは閉区間、それ以外のビンは半開区間になります。

bins引数に[0,1]を指定すると、1個目のビンが「0以上1未満」、2個目のビンが「1以上2以下」の度数を計算します。

In [194]: import numpy as np
In [195]: data=[0, 0, 1]

In [214]: hist, bins = np.histogram(data, bins=[0, 1, 2])

In [215]: hist
Out[215]: array([2, 1])

In [216]: bins
Out[216]: array([0, 1, 2])

ビンの幅からbinsを計算する。

ビンの幅からビンの境界を計算する関数を作成しました。
rangeで算出したビンの境界の右端が最大値に一致するときだけ、ビンの数を増やしています。

def get_bin_edges(min_value: int, max_value: int, bin_width:int) -> list:
    bin_edges = list(range(min_value, max_value + bin_width, bin_width))

    if bin_edges[-1] == max_value:
        bin_edges.append(bin_edges[-1] + bin_width)

    return bin_edges
In [242]: get_bin_edges(0,4,2)
Out[242]: [0, 2, 4, 6]

In [243]: get_bin_edges(0,3,2)
Out[243]: [0, 2, 4]

上記のget_bin_edges関数に小数を渡すことはできません。小数を渡すとrange()でエラーが発生します。

In [285]: get_bin_edges(0, 0.2, 0.1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[285], line 1
----> 1 get_bin_edges(0, 0.2, 0.1)

Cell In[282], line 2, in get_bin_edges(min_value, max_value, bin_width)
      1 def get_bin_edges(min_value: int, max_value: int, bin_width:int) -> list:
----> 2     bin_edges = list(range(min_value, max_value + bin_width, bin_width))
      4     if bin_edges[-1] == max_value:
      5         bin_edges.append(bin_edges[-1] + bin_width)

TypeError: 'float' object cannot be interpreted as an integer

小数にも対応するのであれば、range()でなくnumpy.arange()を使う必要があります。
ただし小数の場合は等価演算が期待通りにならないときがあるので、最初からビンの個数を多めに作るのがよさそうです。

def get_bin_edges2(min_value: float, max_value: float, bin_width:float) -> numpy.ndarray:
    bin_edges = numpy.arange(min_value, max_value + bin_width*2, bin_width)
    return bin_edges
In [270]: get_bin_edges2(0, 0.2, 0.1)
Out[270]: array([0. , 0.1, 0.2, 0.3])

In [271]: get_bin_edges2(0, 0.3, 0.1)
Out[271]: array([0. , 0.1, 0.2, 0.3, 0.4])

In [272]: get_bin_edges2(0, 0.4, 0.1)
Out[272]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6])

In [273]: get_bin_edges2(0, 4, 2)
Out[273]: array([0, 2, 4, 6])

In [277]: get_bin_edges2(0, 3, 2)
Out[277]: array([0, 2, 4, 6])

参考にしたサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?