How do I convert a Pandas dataframe from a 'frequency table' format to a flat dataframe format and back again using idiomatic Python?
From:
H E K
0 B B 12
1 B G 3
2 G B 17
3 G G 68
to:
H E
0 B B
1 B B
2 B B
3 B B
4 B B
5 B B
6 B B
7 B B
8 B B
9 B B
10 B B
11 B B
12 B G
13 B G
14 B G
...
and back again!
H E K
0 B B 12
1 B G 3
2 G B 17
3 G G 68
Please advise?
new_df = df.loc[df.index.repeat(df['K'])].reset_index(drop=True)like this answerdf = new_df.groupby(['H', 'E']).size().reset_index(name='K')like this answer.dropthe columnnew_df = df.loc[df.index.repeat(df['K'])].drop(columns='K').reset_index(drop=True)