Python 将值放置在列标题和行标题上
这段代码运行得非常好。我只需要帮助将矩阵的元组值组合放置在列和行上:Python 将值放置在列标题和行标题上,python,list,dictionary,matrix,markov,Python,List,Dictionary,Matrix,Markov,这段代码运行得非常好。我只需要帮助将矩阵的元组值组合放置在列和行上: 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 t
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
这将正确打印出您指定的标题。这有点困难,因为您希望标头不会打印出最后一个值,但这应该会按预期打印出来
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))
print('\t{}).format(''.join(str(i)表示范围(1,len(矩阵'))))))
对于索引,枚举(矩阵)中的行:
如果指数
如果希望行标题的距离不同,可以始终使用空格而不是制表符(
\t
)。您成功打印了这些值,是什么阻止了您打印标题?这就是我没有想到的。您尝试了什么吗?到底是什么问题?问题是如何附加标题,:-)谢谢Karl,是的,这给了我垂直轴。谢谢。