我的test.txt文件包括:
2 2 4
1 1 3
4 1 1
1 1 1
4 1 2
2 2 1
3 2 3
2 1 1
我的Python代码:
import numpy as np
from numpy.linalg import
import os
A=np.loadtxt("C:\Users\KEMAL\Desktop\piton\test.txt")
n=3
for i in range(0,n):
b=[row[i] for row in A]
D=np.array(b)
size=[len(D),np.max(D)]
B=np.zeros(size)
for i in range(len(D)):
idx=D[i]-1
B[i,idx]=1
U=B.transpose(1, 0)
print U
通过上面编写的代码,这段代码给了我这个:
[[ 0. 1. 0. 1. 0. 0. 0. 0.]
[ 1. 0. 0. 0. 0. 1. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 1. 0. 0. 0.]]
[[ 0. 1. 1. 1. 1. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 1. 1. 0.]]
[[ 0. 0. 1. 1. 0. 1. 0. 1.]
[ 0. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 1. 0.]
[ 1. 0. 0. 0. 0. 0. 0. 0.]]
这不是矩阵!我想将矩阵转换成如下所示,并且每次尝试都失败了。
[[ 0. 1. 0. 1. 0. 0. 0. 0.]
[ 1. 0. 0. 0. 0. 1. 0. 1.]
[ 0. 0. 0. 0. 0. 0. 1. 0.]
[ 0. 0. 1. 0. 1. 0. 0. 0.]
[ 0. 1. 1. 1. 1. 0. 0. 1.]
[ 1. 0. 0. 0. 0. 1. 1. 0.]
[ 0. 0. 1. 1. 0. 1. 0. 1.]
[ 0. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 1. 0.]
[ 1. 0. 0. 0. 0. 0. 0. 0.]]
答案 0 :(得分:0)
尝试这样的事情:
NewU=list()
for i in U:
NewU+=i
print NewU
我不熟悉numpy,所以我不确定它是否有效,但值得一试。
答案 1 :(得分:0)
我建议用以下内容替换你的for循环:
A = np.loadtxt("C:\Users\KEMAL\Desktop\piton\test.txt").T
s = A.max(axis=1).cumsum()
data = np.zeros((int(s[-1]), A.shape[1]))
A[1:] += s[:2, None]
i = (A - 1).astype(int)
j = np.tile(np.arange(A.shape[1]), (A.shape[0], 1))
data[i, j] = 1
因此>>> data
给出了:
array([[ 0., 1., 0., 1., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0., 1., 0., 1.],
[ 0., 0., 0., 0., 0., 0., 1., 0.],
[ 0., 0., 1., 0., 1., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 0., 0., 1.],
[ 1., 0., 0., 0., 0., 1., 1., 0.],
[ 0., 0., 1., 1., 0., 1., 0., 1.],
[ 0., 0., 0., 0., 1., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 1., 0.],
[ 1., 0., 0., 0., 0., 0., 0., 0.]])
这应该更快。如果你想继续使用较慢的for循环解决方案,你应该vstack
生成的数组:
A=np.loadtxt("C:\Users\KEMAL\Desktop\piton\test.txt")
n=3
arrs = []
for i in range(0,n):
b=[row[i] for row in A]
D=np.array(b)
size=[len(D),np.max(D)]
B=np.zeros(size)
for i in range(len(D)):
idx=D[i]-1
B[i,idx]=1
U=B.transpose(1, 0)
arrs.append(U)
np.vstack(arrs)