对于我在 Python 中的面板数据分析,我想检查转换概率。我有人年组合和一些分类变量,例如健康(1=excellent
、2=good
等)。
我需要一个关于从一个状态/类别到另一个状态/类别发生变化的频率的绝对和/或相对频率的汇总表 - 每个人,而不是每列。特别是指标6
和7
之间的健康状态差异不应包括在内,因为它不是一个人内部的转变。
这是一些示例数据:
import pandas as pd
df = pd.DataFrame({'year': ['2003', '2004', '2005', '2006', '2007', '2008', '2009',
'2003', '2004', '2005', '2006', '2007', '2008', '2009'],
'id': ['1', '1', '1', '1', '1', '1', '1',
'2', '2', '2', '2', '2', '2', '2',],
'health': ['3', '1', '2', '2', '5', '1', '1',
'1', '2', '3', '2', '1', '1', '2']}).astype(int)
输出应该如下(计算状态转换的发生次数):
(也许Python中有类似于Stata的xttrans
命令的东西?)
最佳答案
使用 shift
创建新列. where
确保我们在 id
更改时排除它。那么这是crosstab
(或 groupby size,或 pivot_table)来获取计数。
import pandas as pd
#df = df.sort_values(['id', 'year'])
df['health_trans'] = df.health.shift(-1).where(df.id.eq(df.id.shift(-1)))
pd.crosstab(df.health, df.health_trans)
#health_trans 1.0 2.0 3.0 5.0
#health
#1 2 3 0 0
#2 1 1 1 1
#3 1 1 0 0
#5 1 0 0 0
为确保始终列出所有转换,请使用 reindex
.
health = range(1,6)
(pd.crosstab(df.health, df.health_trans)
.reindex(health).reindex(health, axis=1)
.fillna(0).astype(int))
#health_trans 1 2 3 4 5
#health
#1 2 3 0 0 0
#2 1 1 1 0 1
#3 1 1 0 0 0
#4 0 0 0 0 0
#5 1 0 0 0 0
这可能不会像您希望的那样处理 id
丢失几年的情况。看起来你有一个平衡的面板开始,在这种情况下没有问题。
关于python - 如何计算转移概率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56704615/