【问题标题】:numpy: finding all pairs of numbers in a matrix that suffice on neighboring conditionnumpy:找到矩阵中满足相邻条件的所有数字对
【发布时间】:2018-02-20 23:30:18
【问题描述】:

假设你有一个矩阵:

import numpy as np
mat = np.array([[0, 0, 1], [2, 0, 1], [1, 0, 3]])

并且您想要检索此矩阵中彼此相邻的所有数字对,不等于并忽略零。在这种情况下,这将是 3 & 1 和 2 & 1,但我希望能够将其应用于非常大的矩阵。非常感谢任何帮助,谢谢!

【问题讨论】:

  • 您当前的尝试有什么问题?
  • 我是如何尝试解决这个问题的,只是循环遍历每一行和每一列,并在矩阵等的边缘使用单独的 if 语句。这似乎是一种不聪明的方法来解决这个问题,所以我想也许有人有更聪明的方法:)
  • 忽略“不等于”还是等于?
  • 不等于并忽略零。我很困惑:)

标签: python numpy


【解决方案1】:

这应该可以解决问题,尽管不可否认,它不是最优雅的;我在一个 1000x1000 的随机整数矩阵上对其进行了测试,它非常快(仅仅一秒钟多一点)。我不确定您是如何考虑输出的,因此我将其放入了一个名为 res 的列表中。

import numpy as np
# To test on larger array
mat = np.array(np.random.random_integers(0, 9, 1000 * 1000)).reshape(1000, 1000)
res = []

for a in mat:
    # Take out the zeros
    no_zeros = a[a!=0]
    if len(no_zeros) > 1:
        for i in range(len(no_zeros) - 1):
            # Only append pairs of non-equal neighbours
            if no_zeros[i] != no_zeros[i+1]:
                res.append((no_zeros[i], no_zeros[i+1]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 2012-01-14
    • 2011-07-20
    • 1970-01-01
    • 2015-05-18
    • 2020-02-11
    • 2018-10-06
    相关资源
    最近更新 更多