I have the following dataframe
import pandas as pd
foo = pd.DataFrame({'id': [1,1,1,1,2,2,2,2,3,3,3,3],
'time': [1,2,3,4,1,2,3,4,1,2,3,4],
'cat': ['a', 'a', 'b', 'c',
'a', 'b', 'b', 'b',
'c', 'b', 'c', 'b']
})
I want to calculate, how many times the cat changes from one time to the next, by id
So:
- for
id == 1,catchangesfrom a to a1 time,from a to b1 time andfrom b to c1 times - for
id == 2,catchangesfrom a to b1 time, andfrom b to b 2times - for
id == 3,catchangesfrom c to b 2times, andfrom b to c 1time
Any ideas how I could compute that ?
Ideally the output should look something like:
pd.DataFrame({'id': [1,2,3],
'a to a': [1,0,0],
'a to b': [1,1,0],
'a to c': [0,0,0],
'b to a': [0,0,0],
'b to b': [0,2,0],
'b to c': [1,0,1],
'c to a': [0,0,0],
'c to b': [0,0,2],
'c to c': [0,0,0]
})