【问题标题】:How to write recursive search with numpy where function?如何使用 numpy where 函数编写递归搜索?
【发布时间】:2019-10-02 00:50:59
【问题描述】:

我正在编写一个递归函数来查找索引对。 在我的示例中,向量 i 和 j 是矩阵的非零元素的 i 和 j 索引。

现在我想找到“唯一”的索引对,这样我就可以对其对角线形式的矩阵进行排序。或者至少消除零元素

我用 numpy 写了一个函数。

import numpy as np

i = np.array([0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8])
j = np.array([0, 3, 4, 0, 2, 4, 1, 5, 2, 6, 8, 3, 8, 4, 5, 7, 4, 6, 7, 8])
numbers = np.array([-1.])

def iterate(i, j, iter, numbers):
    ii, = np.where(i == iter)
    jj, = np.where(j[ii] != numbers)

    try:
        for jjj in jj:
            numbers = np.append(numbers, [jjj])
            if iter < np.amax(i)+1:
                iterate(i, j, iter+1, numbers)
            else:
                return numbers
    except:
        print("exception")

如果我的迭代变量超过 i 中最大值的长度,我会期望返回。 问题是 numpy 为多重比较操作抛出错误:

jj, = np.where(j[ii] != numbers)

【问题讨论】:

  • 错误是什么? jj,=... 仅在 where 测试一维数组时有效。拆包逗号是不可原谅的。
  • python __main__:11: DeprecationWarning: elementwise != comparison failed; this will raise an error in the future.
  • 什么是numbersj[ii]

标签: python numpy recursion indexing


【解决方案1】:

通过在ii,= 行之后添加print,我看到numbers[-1,0],并且:

In [76]: j[[3,4,5]]                                                             
Out[76]: array([0, 2, 4])
In [77]: j[[3,4,5]]!=np.array([-1,0])                                           
/usr/local/bin/ipython3:1: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
  #!/usr/bin/python3
Out[77]: True

它不喜欢将 3 元素数组与 2 元素数组进行比较。过去它容忍了不匹配,但将来它会被禁止。

你想在这里做什么?每次附加 numbers 都会变长,但 j[ii] 会因 i 而异。

您是否正在寻找两个数组之间的精确匹配?元素方面?二维笛卡尔匹配?

【讨论】:

  • 我只想从 j 中取出一个唯一整数,用于所有 i。例如 im 检查 i 中的 0 整数,所以我有 j 中的三个选项可供选择。这将从 j 获取 0 并将其附加到数字。下一次迭代检查 i 并得到 1,现在它应该在 j 中寻找一个伙伴,并且 0 已经占用,所以我想检查 i=1 位置的整数,而不是 0。等等。条件将比 i 的最大值更长。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多