【问题标题】:elementwise boolean testing in a matrix矩阵中的元素布尔测试
【发布时间】:2017-05-06 20:36:18
【问题描述】:

我需要测试数组中的布尔值,并根据答案对矩阵应用元素操作。我似乎得到了 ROW 的布尔答案,而不是单个元素本身。我如何测试并获得每个元素的答案?

我有一个概率矩阵

probs = np.array([[0.1, 0.2, 0.3, 0.3, 0.7],
                  [0.1, 0.2, 0.3, 0.3, 0.7],
                  [0.7, 0.2, 0.6, 0.1, 0.0]])

和一个测试数组矩阵

tst = ([False, False, True, True, False],
       [True, False, True, False, False],
       )
t = np.asarray(tst).astype('bool')

我写的这段代码输出了答案,但显然测试了整行,因为一切都是假的。

for row in tst:
    mat = []
    for row1 in probs:
        temp = []
        if row == True:
            temp.append(row1)
        else: temp.append(row1-1)
        mat.append(temp)

mat
Out[42]: 
[[array([-0.9, -0.8, -0.7, -0.7, -0.3])],
 [array([-0.9, -0.8, -0.7, -0.7, -0.3])],
 [array([-0.3, -0.8, -0.4, -0.9, -1. ])]]

我需要新的矩阵

[[-0.9, -0.8, 0.3, 0.3, -0.3],
 [-0.9, -0.8, 0.3, 0.3, -0.3],
 [-0.3, -0.8, 0.6, 0.1, -1]

对于 tst 中的第一个数组。非常感谢您的帮助!

【问题讨论】:

    标签: python matrix boolean operations


    【解决方案1】:

    如果 test 是 True,则需要保持原样,否则减去 1

    您的循环不起作用,因为您将列表与布尔值进行比较。之后,您将整行加减 1(对所有元素减 1)

    我的解决方案:将布尔行减去值行,但反转 True 和 False(如果为 True,则不减去,如果为 False,则减去):

    for row in tst:
        mat = []
        for row1 in probs:
            mat.append(row1-[not v for v in row])
    
        print(np.asarray(mat))
    

    打印(每次迭代)(请注意,您有 2 个结果,因为您将 2 个真值表与矩阵相结合):

    [[-0.9 -0.8  0.3  0.3 -0.3]
     [-0.9 -0.8  0.3  0.3 -0.3]
     [-0.3 -0.8  0.6  0.1 -1. ]]
    [[ 0.1 -0.8  0.3 -0.7 -0.3]
     [ 0.1 -0.8  0.3 -0.7 -0.3]
     [ 0.7 -0.8  0.6 -0.9 -1. ]]
    

    (我根本不是 numpy 专家,如果这很笨拙,请见谅,欢迎 cmets)

    【讨论】:

    • 谢谢,太好了!
    【解决方案2】:

    这里不需要循环。你有一个数组和一个对应的掩码数组。

    probs[np.invert(tst)]-=1.
    

    面具会给你真正的价值。您不希望错误值因此反转 tst 数组。

    # This would be a longer version, if you are not familiar with the synthax above
    probs[np.invert(tst)]=probs[np.invert(tst)]-1.
    

    如果你想创建一个新的 numpy 数组(你在代码中创建了一个 numpy 数组列表),它会以这种方式工作。

    # copy the numpy array
    mat=np.copy(probs)
    mat[np.invert(tst)]=probs[np.invert(tst)]-1
    

    我建议你先看看初学者教程,如果你知道列表和numpy-arrays之间的区别以及如何处理它们,编程会容易得多。

    https://www.scipy.org/scipylib/faq.html#what-advantages-do-numpy-arrays-offer-over-nested-python-lists https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

    或简短的解释

    Python List vs. Array - when to use?

    【讨论】:

    • =) 是的,我真的应该这样做,不幸的是,这将在 2 天内到期。我在没有python exp和很少的prog exp的情况下进入了深渊。是的!创建一个新数组是我需要的。谢谢。
    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多