python - 使用来自 2 个 numpy 矩阵的数据绘制直方图

标签 python numpy matrix

我有 2 个 numpy 矩阵 AB:

  • A 矩阵的值尽可能只有 1 或 0(ON 或 OFF)。
  • B 矩阵具有整数(最小值 -1)。

我需要在矩阵 B(X-axis) 的元素和它们在矩阵 A 中列为 ON 的频率之间绘制直方图(在相应的位置).

例如:

IF A[1][1] and A[2][2] are 1, 
AND B[1][1] and B[2][2] are 2, 
THEN frequency of 2 should be 2 (similarly for each element of matrix B).

基本上对于 B 中的每个元素,如果 A 中对应的元素为 1,则其频率增加 1。

我处理的矩阵很大 (3992x3992)。如何尽可能高效地执行此操作?

最佳答案

如果 B 中的值都是小的正整数,你可以简单地这样做:

count = np.bincount(B.ravel())
tally = np.bincount(B.ravel(), weights=A.ravel())
freq = tally / count

但是因为你有负数,所以最好安全起见,先通过 np.unique 运行 B:

unq_val, unq_idx = np.unique(B.ravel(), return_inverse=True)
unq_count = np.bincount(unq_idx)
unq_tally = np.bincount(unq_idx, weights=A.ravel())
unq_freq = unq_tally / unq_count

当 numpy 1.9 在接下来的几周内面世时,您可以通过将前两行加入一行来获得额外的性能优势:

unq_val, unq_idx, unq_count = np.unique(B.ravel(), return_inverse=True,
                                        return_counts=True)

之后,您将在 unq_val 中获得 x 值,在 unq_freq 中获得相应的 y 值。在我的系统上,这个组成的数据:

A = np.random.randint(2, size=(3992, 3992))
B = np.random.randint(50, size=(3992, 3992))

整个过程在 0.3 秒内运行而无需通过 unique,而在使用它时仅需 6 秒多一点。

关于python - 使用来自 2 个 numpy 矩阵的数据绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24015883/

相关文章:

r - 点矩阵之间的距离,简单的 if 和 for

python - 散点图中的轴范围

php - 在离线 TideSDK webapp 中将 SVG 导出为 PDF

python - 如何删除不同长度列表列表中的最内层嵌套

python - 对 numpy 矩阵中的字母数字字符串进行排序

r - 如果索引从 1 开始,为什么矩阵允许索引为零?

python - 加载文件中的错误 ylabels

python - Numpy 数组不能在单个 [] 中建立索引

python - 在 for 循环中追加数组

c++ - 两个矩阵之和的逆