将元组转换为具有以下条件的Numpy矩阵:
len(tuple) x len(tuple) (方阵)。(index of the element in the tuple, the value of the element in the tuple)指定的位置的元素应该是一个。例如,我有一个随机元组,如下所示:
# index means row ,value means col
(2,0,1)我使用两个循环将这个元组转换为Numpy数组:
def get_np_represent(result):
two_D = []
for row in range(len(result)):
one_D = []
for col in range(len(result)):
if result[row] == col:
one_D.append(1)
else:
one_D.append(0)
two_D.append(one_D)
return np.array(two_D)产出:
array([[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])但是我有一千万这样的元组,有更快的方法吗?
发布于 2019-07-12 02:23:47
像这样吗?操纵矩阵的速度比循环快得多。
import numpy as np
t = (2, 0, 1)
x = np.zeros([len(t),len(t)])
for i,v in enumerate(t):
x[i, v] = 1
print(x)产出:
[[0. 0. 1.]
[1. 0. 0.]
[0. 1. 0.]]https://stackoverflow.com/questions/56999369
复制相似问题