【发布时间】: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 语句更有效的方法。我在想这可以通过矩阵乘法以某种方式解决?!感谢任何帮助。
【问题讨论】:
-
我想知道这是在什么背景下出现的,因为:(1)我很好奇; (2) 确保我们没有处理 XY 问题 (en.wikipedia.org/wiki/XY_problem)。
标签: python pandas numpy matrix matrix-multiplication