此代码可以正常工作。我只需要一个帮助就可以将矩阵的元组值组合放在列和行上:
from __future__ import division
import seaborn as sns; sns.set()
def transition_matrix(transitions):
states = 1+ max(transitions) #number of states
MAT = [[0]*states for _ in range(states)] #placeholder to shape the matrix based on states
#print('mat', M)
for (i,j) in zip(transitions,transitions[1:]):
#print(i, j)
"""matrix with transition from state i to state j"""
MAT[i][j] += 1
#print("matrix with transition",M)
for row in MAT:
"""calculating probabilities"""
s = sum(row)
if s > 0:
row[:] = [f/s for f in row]
return MAT
#test:
employeeCountperEmployer = [1, 2, 3, 1, 4, 2, 1]
m = transition_matrix(employeeCountperEmployer)
#print(m)
for row in m:
print('|'.join('{0:.2f}'.format(x) for x in row))
这会生成以下内容:
0.00|0.00|0.00|0.00|0.00
0.00|0.00|0.50|0.00|0.50
0.00|0.50|0.00|0.50|0.00
0.00|1.00|0.00|0.00|0.00
0.00|0.00|1.00|0.00|0.00
但是,我想要这个
1 2 3 4
1 0.00|0.00|0.00|0.00|0.00
2 0.00|0.00|0.50|0.00|0.50
3 0.00|0.50|0.00|0.50|0.00
4 0.00|1.00|0.00|0.00|0.00
0.00|0.00|1.00|0.00|0.00
答案 0 :(得分:0)
这应该正确打印出您指定的标题。有点困难,因为您希望标题不会打印出最后一个值,但这应该可以按预期打印出来。
print('\t{}'.format(' '.join(str(i) for i in range(1, len(matrix)))))
for index, row in enumerate(matrix):
if index < len(m) - 1:
print('{}\t'.format(str(index + 1))),
else:
print(' \t'),
print('|'.join('{0:.2f}'.format(x) for x in row))
如果您希望行标题具有不同的距离,则可以始终使用空格代替制表符(\t
)。