I have a dataframe which is like this:
id sub_id count
0 94 1
1 94 9
1 315 7
2 94 4
2 265 1
data = {'id': [0,1,1,2,2],
'sub_id': [94,94,315,94,265],
'count': [1,9,7,4,1]
}
df = pd.DataFrame(data)
And I want it in the following form:
id sub_id1 count_sub_id1 sub_id2 count_sub_id2
0 94 1 NaN NaN
1 94 9 315 7
2 94 4 265 1
Note: Here, every id can have either can have a maximum of two rows, each with different sub_id and their counts.
I tried this df.pivot(index='id',columns='sub_id',values='count') but this is causing all rows in the second column to be expanded as different columns, whereas I only need two columns, with a custom name, ie. only those two rows which exist for each group of ids