python - 根据所选值总结和绘制 ndarrays 列表

标签 python numpy matplotlib histogram probability-distribution

我有一个 ndarray 列表:

list1 = [t1, t2, t3, t4, t5]

每个 t 包括:

t1 = np.array([[10,0.1],[30,0.05],[30,0.1],[20,0.1],[10,0.05],[10,0.05],[0,0.5],[20,0.05],[10,0.0]], np.float64)

t2 = np.array([[0,0.05],[0,0.05],[30,0],[10,0.25],[10,0.2],[10,0.25],[20,0.1],[20,0.05],[10,0.05]], np.float64)

...

现在我想让整个列表为每个 t 获取对应于第一个元素的值的平均值:

t1out = [[0,0.5],[10,(0.1+0.05+0.05+0)/4],[20,(0.1+0.05)/2],[30,0.075]]

t2out = [[0,0.05],[10,0.1875],[20,0.075],[30,0]]

....

在生成 t_1 ... t_n 之后,我想绘制每个 t 的类别概率,其中第一个元素代表类别 (0,10,20,30),第二个元素显示类别的概率这些类出现 (0.1,0.7,0.15,0)。类似于直方图或条形图形式的概率分布,例如:

plt.bar([classes],[probabilities])

plt.bar([item[0] for item in t1out],[item[1] for item in t1out])

最佳答案

这是使用 NumPy 计算的方法:

import numpy as np

def mean_by_class(t, classes=None):
    # Classes should be passed if you want to ensure
    # that all classes are in the output even if they
    # are not in the current t vector
    if classes is None:
        classes = np.unique(t[:, 0])
    bins = np.r_[classes, classes[-1] + 1]
    h, _ = np.histogram(t[:, 0], bins)
    d = np.digitize(t[:, 0], bins, right=True)
    out = np.zeros(len(classes), t.dtype)
    np.add.at(out, d, t[:, 1])
    out /= h.clip(min=1)
    return np.c_[classes, out]

t1 = np.array([[10, 0.1 ], [30, 0.05], [30, 0.1 ],
               [20, 0.1 ], [10, 0.05], [10, 0.05],
               [ 0, 0.5 ], [20, 0.05], [10, 0.0 ]],
              dtype=np.float64)
print(mean_by_class(t1))
# [[ 0.     0.5  ]
#  [10.     0.05 ]
#  [20.     0.075]
#  [30.     0.075]]

附带说明一下,将类值(整数)存储在 float 组中可能不是最佳选择。您可以考虑使用 structured array相反,例如像这样:

import numpy as np

def mean_by_class(t, classes=None):
    if classes is None:
        classes = np.unique(t['class'])
    bins = np.r_[classes, classes[-1] + 1]
    h, _ = np.histogram(t['class'], bins)
    d = np.digitize(t['class'], bins, right=True)
    out = np.zeros(len(classes), t.dtype)
    out['class'] = classes
    np.add.at(out['p'], d, t['p'])
    out['p'] /= h.clip(min=1)
    return out

t1 = np.array([(10, 0.1 ), (30, 0.05), (30, 0.1 ),
               (20, 0.1 ), (10, 0.05), (10, 0.05),
               ( 0, 0.5 ), (20, 0.05), (10, 0.0 )],
              dtype=[('class', np.int32), ('p', np.float64)])
print(mean_by_class(t1))
# [( 0, 0.5  ) (10, 0.05 ) (20, 0.075) (30, 0.075)]

关于python - 根据所选值总结和绘制 ndarrays 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525747/

相关文章:

numpy - 按条件更新 numpy 数组行

python - Seaborn 条形图图例标签失去颜色

python - 使用 Brother QL-800 标签打印机打印标签

python:如何将元组列表转换为numpy数组

python - Generator Comprehension 和 List Comprehension 的迭代方式不同

python 在情节之上绘图

python - 绘制二维数据 : heatmap with different colormaps

Python:如何在 Flask 中显示 matplotlib

python - 如何使用任何分类器对每个数据点由一组浮点值组成的数据进行分类?

python - 使用python查找mongo中丢失文档的有效方法