How to separate entries based on rows and columns in pandas dataframe

Viewed 78

I have a dataframe that looks like this:

   '0' '1' '2'
0   5   4   0
1   3   0   0
2   1   0   2

Where the name of the columns ('0', '1', '2', ...) represent user ids, the index represents movie ids, and each entry denotes the rating given by the user to that movie.

I would like to make a new dataframe, based on the previous one, that is like this:

  user_id   movie_id  rating
0   0         0         5
1   0         1         3
2   0         2         1
3   1         0         4
4   1         1         0
5   1         2         0
6   2         0         0
7   2         1         0
8   2         2         2

I am new to pandas and was wondering how to do this without iterating through all the entries.

1 Answers

You can get it with stack(), and then reset_index():

df = df.stack().reset_index()
df.columns = ['user_id','movie_id','rating']
print(df)
   user_id  movie_id  rating
0        0         0       5
1        0         1       4
2        0         2       0
3        1         0       3
4        1         1       0
5        1         2       0
6        2         0       1
7        2         1       0
8        2         2       2
Related