Building a Transition Matrix using words in Python/Numpy

后端 未结 6 1740
抹茶落季
抹茶落季 2020-12-09 22:32

Im trying to build a 3x3 transition matrix with this data

days=[\'rain\', \'rain\', \'rain\', \'clouds\', \'rain\', \'sun\', \'clouds\', \'clouds\', 
  \'rai         


        
6条回答
  •  囚心锁ツ
    2020-12-09 23:23

    Below another alternative using pandas. Transitions list can be replaced with 'rain','clouds' etc.

    import pandas as pd
    transitions = ['A', 'B', 'B', 'C', 'B', 'A', 'D', 'D', 'A', 'B', 'A', 'D'] * 2
    df = pd.DataFrame(columns = ['state', 'next_state'])
    for i, val in enumerate(transitions[:-1]): # We don't care about last state
        df_stg = pd.DataFrame(index=[0])
        df_stg['state'], df_stg['next_state'] = transitions[i], transitions[i+1]
        df = pd.concat([df, df_stg], axis = 0)
    cross_tab = pd.crosstab(df['state'], df['next_state'])
    cross_tab.div(cross_tab.sum(axis=1), axis=0)
    

提交回复
热议问题