Python 如何获得真矩阵
我对这个矩阵有疑问:Python 如何获得真矩阵,python,Python,我对这个矩阵有疑问: A=([[2, 3, 4, 2, 1, 3, 4, 1, 3, 2 ]]) 我想从A中获得另一个矩阵,如下所示: B=([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0]]) 我为此而写: import numpy as np n=np.matr
A=([[2, 3, 4, 2, 1, 3, 4, 1, 3, 2 ]])
我想从A中获得另一个矩阵,如下所示:
B=([[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0]])
我为此而写:
import numpy as np
n=np.matrix('[2, 3, 4, 2, 1, 3, 4, 1, 3, 2]')
c=np.matrix('[0, 0, 0, 0]')
d=np.zeros((1,4))
for i in np.nditer(n):
h=d.itemset((0,i-1),1)
print d
但我得到了如下错误的矩阵
[[ 0. 1. 0. 0.]]
[[ 0. 1. 1. 0.]]
[[ 0. 1. 1. 1.]]
[[ 0. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]]
如何获得真实(B)矩阵???这将帮助您:
from pprint import pprint
A=[[2, 3, 4, 2, 1, 3, 4, 1, 3, 2 ]]
B = [[0]*4 for _ in range(len(A[0]))]
for i,val1 in enumerate(B[:]):
B[i][A[0][i]-1]=1
pprint(B)
输出:
[[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0]]
简单的numpy解决方案,循环可能会被矢量化操作取代,以获得更好的性能 测试用例中出现错误,第七行应该是
[0,0,0,1]
,而不是[0,1,0,1]
import numpy as np
n = np.matrix([2, 3, 4, 2, 1, 3, 4, 1, 3, 2])
expected = np.array([[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0]])
def make_result(input_vector):
output = np.zeros((input_vector.shape[1], np.max(input_vector)))
for idx, value in enumerate(np.nditer(n)):
output[idx, value - 1] = 1
return output
result = make_result(n)
assert (expected == result).all()
如果列少行多,按列查找可能会更快
import numpy as np
n=np.matrix('[2, 3, 4, 2, 1, 3, 4, 1, 3, 2]')
d=np.zeros((n.shape[1],4),dtype=int)
for j in range(4):
d[:,j] = n==j+1 # True->1, False ->0
print d
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
[0 1 0 0]
[1 0 0 0]
[0 0 1 0]
[0 0 0 1]
[1 0 0 0]
[0 0 1 0]
[0 1 0 0]]
谢谢你的关注。这对我真的很有帮助,再次感谢,不管这不是一个numpy矩阵。因此,您将失去所有性能优势。行
[0,1,0,1]
正确吗?简短回答:将d=np.zero((1,4))
放入for
循环中,这样1就不会累积。但是你仍然没有创建一个矩阵,只是打印出它的行。请参阅各种答案。