Flo
Flo

Reputation: 159

Python transition matrix

I have a list looking like this:

[2, 1, 3, 1, 2, 3, 1, 2, 2, 2]

What I want is a transition matrix which shows me the sequence like:

and so on...

((0,2,1), (1,2,1), (2,0,0))

Is there a premade module go get this?

Upvotes: 4

Views: 7804

Answers (1)

tktk
tktk

Reputation: 11734

I don't know if there's a module, but I'd go with this code, which is easily generalizeable:

import numpy as np
from collections import Counter
a = [2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
b = np.zeros((3,3))
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1,y-1] = c
print b
array([[ 0.,  2.,  1.],
       [ 1.,  2.,  1.],
       [ 2.,  0.,  0.]])

With no numpy installed:

b = [[0 for _ in xrange(3)] for _ in xrange(3)]
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1][y-1] = c

print b
[[0, 2, 1], [1, 2, 1], [2, 0, 0]]

A few details of what's going on, if needed:

  1. zip(a, a[1:]) gets all the pairs of consecutive numbers.
  2. Counter counts how many times each pair appears
  3. The for loop simple converts the dictionary Counter produces into the matrix / list of lists you requested

Upvotes: 13

Related Questions