【问题标题】:Numpy Matrix If/Else Classification?Numpy Matrix If/Else 分类?
【发布时间】:2019-04-03 03:32:09
【问题描述】:

假设我有一个矩阵 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 的组合。

# 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 上的结果连接。

 # 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 语句更有效的方法。我在想这可以通过矩阵乘法以某种方式解决?!感谢任何帮助。

【问题讨论】:

标签: python pandas numpy matrix matrix-multiplication


【解决方案1】:

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

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 留给读者作为练习。 :)

附:在此示例中,我使用了以下 outcomes 向量:

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

附言我刚刚注意到我的代码从右到左读出 base-2 数字,而不是从左到右更自然(对我而言)。这不是一个真正的问题,而且很容易改变(也留给读者作为练习)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 2017-07-17
    相关资源
    最近更新 更多