如何计算python中从一种状态到另一种状态的转换次数?

如何计算python中从一种状态到另一种状态的转换次数?,python,pandas,Python,Pandas,这是我的数据帧。我想创建一列,提供这些状态之间的转换次数 ------- Id Mode G18 Start G18 None G18 Start G18 Start G18 Cool ... G50 Mod Cool G50 Mod Cool G50 Mod Cool G50 Mod Cool G50 Mod Cool 我通过移动值创建了一列: Id Mode trans

这是我的数据帧。我想创建一列,提供这些状态之间的转换次数

-------
Id     Mode  
G18   Start   
G18   None    
G18   Start   
G18   Start   
G18   Cool    
...

G50   Mod Cool  
G50  Mod Cool   
G50   Mod Cool  
G50   Mod Cool  
G50   Mod Cool  
我通过移动值创建了一列:

Id    Mode     trans
G18   Start    Heat
G18   Heat     Start
G18   Start    Start
G18   Start    Cool
G18   Cool     Cool
....
G50   ModCool   ModCool
G50   ModCool   ModCool
G50   ModCool   ModCool
G50   ModCool   ModCool
G50   ModCool   ModCool
我编写代码,以字典的形式获取计数:

groups = new.groupby(['Mode', 'trans'])
counts = {i[0]:(len(i[1]) if i[0][0] != i[0][1] else 0) for i in groups}
#counts = {i[0]:len(i[1]) for i in groups} # count (Start,Start)
counts
因为我在代码中使用了dictionary,所以这会在dictionary中给出结果

{Start,Start:0
Start,Heat:1
Start,Cool:2}

但是我想创建一个列“count”,它只提供每个id在这些模式之间的转换次数。有人能帮忙吗?

假设您的数据帧的名称是
df
。如果我理解正确,如果给定行的
df.Mode
值与移位值不同,就会发生转换。因此,您可以添加一个布尔列,指示转换:

df['transition']=(df.Mode!=df.trans)
然后,通过对该列求和,可以得到转换的总数:

sum(df.transition)
或者,要将累计转换数添加为新列,请执行以下操作:

df['count']=df.transition.cumsum()
要获取每个
Id
的编号,您可以执行
groupby

df.groupby('Id').sum()

这个问题很不清楚。请以输入和预期输出的形式清楚地提出您的问题。谢谢