返回满足特定条件的多维数组的SUBSET?

时间:2017-12-04 19:54:00

标签: python arrays python-2.7 multidimensional-array

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

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.

我不确定我设定的'条件'是否是正确的方法,所以有人可以帮助引导我朝着正确的方向前进吗? 随意请求更多说明。

1 个答案:

答案 0 :(得分:1)

这样做的方法是:

每行[{1}}

上的此计算x²+y²-z²
(axis=1)

使用source code

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)

您的情况不佳:如果In [3]: mm[goods] Out[3]: array([[ 5, 12, 13], [ 3, 4, 5], [ 8, 15, 17]]) np.any(z) == np.any(zz)不是空向量,则zz为真。

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