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:
How often is a 1 followed by a 3
How often is a 2 followed by a 1
and so on...
((0,2,1), (1,2,1), (2,0,0))
Is there a premade module go get this?
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:
zip(a, a[1:])
gets all the pairs of consecutive numbers.Counter
counts how many times each pair appearsCounter
produces into the matrix / list of lists you requestedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With