Python numpy:每6行检查1个元素

Python numpy:每6行检查1个元素,python,numpy,Python,Numpy,我需要这样的东西: arr = array([[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0,

我需要这样的东西:

arr = array([[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0,
        0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
        0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,
        0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,
        0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1,
        0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]])
其中,每行包含36个元素,每行中的6个元素表示一个隐藏行,而该隐藏行只需要一个
1
,其他所有位置都需要一个
0
。换句话说,每个mod 6条目只需要一个
1
。这是我对
arr
的要求


我有一个表,用于计算每行的“适合度”值。就是我有一个

table = np.array([10, 5, 4, 6, 5, 1, 6, 4, 9, 7, 3, 2, 1, 8, 3,
                          6, 4, 6, 5, 3, 7, 2, 1, 4, 3, 2, 5, 6, 8, 7, 7, 6, 4, 1, 3, 2])
table = table.T
我将把
arr
的每一行乘以
table
。该乘法的结果,即
1x1
矩阵,将被存储为相应行的“适合度”值除非该行不符合上述要求,否则应返回0

应该返回的内容的一个示例是

result = array([5,12,13,14,20,34])
我需要一个方法来做到这一点,但我对numpy来说太新了,不知道怎么做

(我假设你想要上半场你要求的东西)

我相信存在更好或更优雅的解决方案,但我认为这就是我能做到的

np.all(arr[:,6] == 1) and np.all(arr[:, :6] == 0) and np.all(arr[:, 7:])

或者,您可以构造数组(使用0和1),然后与它进行比较,比如使用。

我也不是100%确定您的问题,但我会尽我所能回答

既然你说你的矩阵有“隐藏行”,为了检查它是否格式良好,最简单的方法似乎就是重新塑造它:

# First check, returns true if all elements are either 0 or 1
np.in1d(arr, [0,1]).all()
# Second check, provided the above was True, returns True if
# each "hidden row" has exactly one 1 and other 0.
(arr.reshape(6,6,6).sum(axis=2) == 1).all()
这两个检查都会为您的
arr
返回“True”

现在,我的理解是,对于36个元素的每一个“大”行,需要一个标量积和“表”向量,除非“大”行有一个格式不正确的“隐藏的小”行。在这种情况下,我会这样做:

# The following computes the result, not checking for integrity
results = arr.dot(table)
# Now remove the results that are not well formed.
# First, compute "large" rows where at least one "small" subrow
# fails the condition.
mask = (arr.reshape(6,6,6).sum(axis=2) != 1).any(axis=1)
# And set the corresponding answer to 0
results[mask] = 0
但是,对数据运行此代码会返回答案

数组([38,31,24,24,32,20])


这不是你提到的;我是否误解了您的要求,或者示例基于不同的数据?

您所说的“检查此项”是什么意思?您需要测试给定的数组是否是这种形式的,还是需要创建这样的数组?请提供您尝试的步骤和结果使用
。重塑(-1,6,6)
,然后您可以沿
1求和,将结果与
1
进行比较,并使用
np。结果布尔数组上的所有
。添加的澄清@srjI无法准确理解您想要的内容。对于上半部分,我认为“np.all(arr[:,6]==1)和np.all(arr[:,:6]==0)和np.all(arr[:,7:])”应该有效。我几乎可以肯定有更好的方法:)。