Python transition matrix

别来无恙 提交于 2019-12-04 11:10:37

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!