基本上采用一个多维数组并检查数组的第三列是否是第一列和第二列的斜边。这是我到目前为止的代码。我在评论中添加了一些内容,以便于更好地理解正在发生的事情。
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.
我不确定我设定的“条件”是否是解决此问题的正确方法,所以有人可以帮助引导我走向正确的方向吗? 请随时要求更多说明。
最佳答案
实现这一点的矢量方法是:
此计算每行上的 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]])
您的情况不好:如果 zz
和 z
,np.any(z) == np.any(zz)
为 true不是零向量。
np.array([condition, mm])
在这里 np.array ([ True, [[5....]] ])
,它触发错误消息。
关于python - 返回满足特定条件的多维数组的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641005/