python - 操作直方图 bins Python

标签 python numpy histogram median

我试图在 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/

相关文章:

python - 计算 pandas 数据框中的日期时间间隔之间有多少个实例

python - 如何使 @decorator 和 @decorator(args) 共享相同的名称?

python - 将 3D 列表转换为 3D NumPy 数组

python - 如何绘制 3d 直方图

r - ggplot2 中具有等面积箱的直方图

python - 转置嵌套生成器

python - 太多的 if 语句

python - 二维 numpy 数组中的阈值

python - 将 df.apply() 与 Pandas MuliIndex 一起使用/对分层索引行执行操作?

python - 将高斯拟合到 ROOT 直方图