【问题标题】:Plotting Histogram using data from 2 numpy matrices使用来自 2 个 numpy 矩阵的数据绘制直方图
【发布时间】:2014-06-03 13:00:16
【问题描述】:

我有 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)。如何尽可能高效地做到这一点?

【问题讨论】:

  • 请提供SSCCE 供我们使用。
  • 通过编写几行代码给出示例数据(AB)比用文字描述数据要好得多。

标签: python numpy matrix


【解决方案1】:

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

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

但是因为你有负数,所以最好安全一点,先运行Bnp.unique

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

【讨论】:

  • 在此之后绘制直方图我在 matplotlib 中使用 unq_val 和 ung_freq?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 2021-11-23
  • 2019-05-04
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多