【问题标题】:Returning a SUBSET of a multidimensional array that satisfies a particular condition?返回满足特定条件的多维数组的子集?
【发布时间】:2018-05-18 08:52:13
【问题描述】:

基本上取一个多维数组并检查数组的第3列是否是第一列和第二列的斜边。这是我到目前为止的代码。我在 cmets 中添加了一些内容,以便更好地了解正在发生的事情。

import numpy
import random

def triple(mm):
    mm=np.asanyarray(mm) # I think this is how we specify that the paremeter should be an array, however,
    # it's possible the parameter isn't just mm, it could be 'j', 'qw', 'mm1', whatever. I'm not sure
    # how to work that while specifying the parameter must be array.
assert mm.ndim == 2 # we want mm or w/e the name of the parameter to be a 1 multidimensional array
assert mm.shape[1] == 3 # we want 3 columns, with any number of rows 
    x = mm[:,0]
    y = mm[:,1]
    z = mm[:,2] # 3rd column is to be checked to see if its's the hypotenuse of 1st & 2nd columns   
    zz = np.hypot(x,y)
    condition = np.any(z) == np.any(zz)
    return np.array([condition, mm]) # I'm not sure how to specify it here, that we want the function to return a subset
        # of the original multi-dim array, where the 3rd column is in fact the hypotenuse of the first and 
        # second columns. And we want to exclude the rows that don't satisfy this condition.

我想检查一下:

mm = np.array([[5,5,5],[5,12,13],[3,4,5],[5,11,21],[8,15,17]])
triple(mm)

但我得到的错误是:

ValueError: setting an array element with a sequence.

我不确定我设置的“条件”是否是解决此问题的正确方法,所以有人可以帮助我朝着正确的方向前进吗? 随时要求更多说明。

【问题讨论】:

    标签: python arrays python-2.7 multidimensional-array


    【解决方案1】:

    一个向量化的方法是:

    此计算 x²+y²-z² 在每一行 (axis=1)

    In [1]: goods=(mm*mm*[1,1,-1]).sum(axis=1)==0
    
    
    In [2]: goods
    Out[2]: array([False,  True,  True, False,  True], dtype=bool)
    

    还有boolean indexing :

    In [3]: mm[goods]
    Out[3]: 
    array([[ 5, 12, 13],
           [ 3,  4,  5],
           [ 8, 15, 17]])
    

    您的条件不好:如果zzz 不是空向量,则np.any(z) == np.any(zz) 为真。

    np.array([condition, mm]) 在这里是 np.array ([ True, [[5....]] ]) ,它会触发错误消息。

    【讨论】:

    • 但我想要的是返回满足条件的行的输出(基本上返回所有毕达哥拉斯三元组)。所以应该是:array([[5,12,13], [ 3,4,5], [8,15,17]])
    • 已编辑。使用布尔索引。
    • 好的,它可以工作,但我不太了解goods 是如何运作的?喜欢它的逻辑...
    • 轴的作用是什么?
    • 那么mm*mm*[1,1,-1]) 是什么?你为什么要乘(?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2013-03-05
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多