python - 返回满足特定条件的多维数组的子集?

标签 python arrays python-2.7 multidimensional-array

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

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]])

您的情况不好:如果 zzznp.any(z) == np.any(zz) 为 true不是零向量。

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

关于python - 返回满足特定条件的多维数组的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641005/

相关文章:

python - 渲染灰色纹理而不是颜色

python - DefaultDict 在两种情况下的行为都不同

python - python threading.Lock() 是否锁定所有需要锁定的东西?

Python NoneType 对象不可下标

python - 在字典中存储逻辑条件并将它们传递给 if 语句

PHP 非法数组键类型警告 (PHPStorm)

Java 字符数组 append 错误

c# - ASP.Net MVC RouteData 和数组

python - 使用用户定义的键返回无的列表排序

python - 在 Django 中,不活动时自动注销的用户仍显示为事件使用