我试图在 np.histrogram
函数生成的 bin 范围内找到值的中值。我将如何仅在 bin 范围内选择值并对这些特定值进行操作?以下是我的数据示例以及我正在尝试执行的操作:
x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
y 值可以与任何类型的 x 值相关联,例如:
hist, bins = np.histogram(x)
hist = [129, 126, 94, 133, 179, 206, 142, 147, 90, 185]
bins = [0., 0.09999926, 0.19999853, 0.29999779, 0.39999706,
0.49999632, 0.59999559, 0.69999485, 0.79999412, 0.8999933,
0.99999265]
因此,我试图在生成的第一个 bin 中找到 129 个值的中值 y 值,等等。
最佳答案
一种方法是使用 pandas.cut()
:
>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(444)
>>> x = np.random.randint(0, 25, size=100)
>>> _, bins = np.histogram(x)
>>> pd.Series(x).groupby(pd.cut(x, bins)).median()
(0.0, 2.4] 2.0
(2.4, 4.8] 3.0
(4.8, 7.2] 6.0
(7.2, 9.6] 8.5
(9.6, 12.0] 10.5
(12.0, 14.4] 13.0
(14.4, 16.8] 15.5
(16.8, 19.2] 18.0
(19.2, 21.6] 20.5
(21.6, 24.0] 23.0
dtype: float64
如果您想继续使用 NumPy,您可能需要查看 np.digitize()
。
关于python - 操作直方图 bins Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292680/