python - Numpy 矩阵 If/Else 分类?

标签 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 上的结果连接起来。

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

最佳答案

首先,从您的描述来看,该元素似乎不能为零,所以让我们假设这一点(不失一般性)。

2**n 种可能的符号组合(如果允许零,则为 3**n),其中 n 是数字列。您可以将这些编码到向量中,称为下面的结果

接下来我将展示如何应用矩阵乘法来解决这个问题。

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

附注我在此示例中使用了以下结果向量:

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

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

关于python - Numpy 矩阵 If/Else 分类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53058416/

相关文章:

python - 计算两列中任一列中字符串出现次数的矢量化方法

python - 导入SWIG+python模块报错"undefined symbol"

python - Django ModelForm 复选框小部件

python - python 可以添加、运行和删除 VBA 宏以在没有中间保存步骤的情况下表现出色吗?

python - pandas 数据框中有效值(非空行)的移动平均值

python - 通过For循环修改Pandas系列

Python Pandas 从宽到长格式更改,列标题拆分

python - 获取列表升序的索引

python - 如何为 gedit 编写 python 命令?

python - 随机梯度下降和性能