-1

this code works perfectly fine. I just need a help to place the tuple values combination of matrix on the column as well as rows:

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))

this generates following:

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

However, I wanted this as

        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
lpt
  • 931
  • 16
  • 35

1 Answers1

0

This should properly print out the headers as you specified. It is a little difficult since you expect the header to not print out the last value, but this should print it out as expected.

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))

You can always use spaces instead of the tab (\t) if you'd like the row headers to be a different distance.

Karl
  • 1,664
  • 2
  • 12
  • 19