Skip to main content
 首页 » 编程设计

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

2025年05月04日7zdz8207

我有 2 个 numpy 矩阵 A 和 B:

  • 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 秒多一点。