numpy矩阵是否/其他分类?

时间:2018-10-30 06:17:33

标签: python pandas numpy matrix matrix-multiplication

比方说,我有一个矩阵M,该矩阵具有3个(或n个)负/正值列:

M=[[-0.5,0.5,-1],
   [1,-0.5,-1],
   [-1,-1,-0.5],
   [0.5,1-,1],
   [1,0.5,1]]

我现在想按条件对每一行进行分类,并用结果创建第四列。条件是<0和> 0的组合。

# Just an example of conditions
# The actual amount of conditions is 2^n with n being the amount of columns and 2 because there are variants (<0 and >0)
results = []
if row[0]<0 and row[1]>0 and row[2]>0:
    results.append(1)
elif row[0]>0 and row[1]>0 and row[2]>0:
    results.append(1)
elif row[0]<0 and row[1]<0 and row[2]<0:
    results.append(-1)
elif row[0]<0 and row[1]<0 and row[2]>0:
    results.append(-1)
else:
    results.append(1)

“结果”列表是要附加到M的列,因此输出看起来像这样(每行的第四个值是条件的结果),因此基本上矩阵M与轴1上的结果串联在一起。 / p>

 # Just example values, not matching the rules above
 M=[[-0.5,0.5,-1,1],
   [1,-0.5,-1,-1],
   [-1,-1,-0.5,-1],
   [0.5,1-,1,1],
   [1,0.5,1,1]]

我要寻找的是比对矩阵的每一行执行if / else语句更有效的方法。我以为这可以用矩阵乘法解决?感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

首先,根据您的描述,该元素似乎不能为零,因此我们假设(不失一般性)。

存在2**n个可能的符号组合(如果允许零,则为3**n,其中n是列数。您可以将它们编码为以下称为outcomes的向量。

下面将说明如何应用矩阵乘法来解决此问题。

M作为输入矩阵:

In [36]: M
Out[36]:
array([[-0.5,  0.5, -1. ],
       [ 1. , -0.5, -1. ],
       [-1. , -1. , -0.5],
       [ 0.5,  1. , -1. ],
       [ 1. ,  0.5,  1. ]])

In [37]: m, n = M.shape

现在,我们:

  • M转换成二进制矩阵,对每个元素的符号进行编码;
  • 读出结果的每一行,就好像它是以2为底的数字一样。

这为M的每一行提供了相应结果的索引:

In [40]: outcome_index = np.matmul(M > 0, [2**i for i in range(n)])

In [41]: outcome_index
Out[41]: array([2, 1, 0, 3, 7])

最后,我们使用索引来计算新列:

In [42]: outcomes[outcome_index]
Out[42]: array([-1, -1,  1,  1, -1])

将列添加到M留给读者练习。 :)

P.S。在此示例中,我使用了以下outcomes向量:

In [43]: outcomes
Out[43]: array([ 1, -1, -1,  1,  1, -1, -1, -1])

P.P.S。我刚刚注意到,我的代码从右到左读取了以2为基数的数字,而不是从左到右(对我而言)更自然。这并不是真正的问题,并且很容易更改(也留给读者练习)。