Adil  Zhakypbek
Adil Zhakypbek

Reputation: 11

Change pandas dataframe format

I am new to python and can't seem to find a solution. Currently, my pandas dataframe is of format:

     841  818  813  800  788
399  3.0  4.0  3.0  NaN  NaN
400  NaN  NaN  NaN  3.0  3.0

Where 399 and 400 are unique ids. I am trying to make it so that unique ids will repeat until all columns are separated as rows. Like this:

399  841  3.0
399  818  4.0
...
400  841  NaN
400  818  NaN
...

Any help would be appreciated, thanks!

Upvotes: 0

Views: 74

Answers (1)

Adil  Zhakypbek
Adil Zhakypbek

Reputation: 11

Thanks, Quang Hoang, this solution does work! Here is a straight-forward answer for those who might search for this in the future if your pandas dataframe is named "data_df" then just do this:

data_df = data_df.stack(dropna=False).reset_index()

P.S.: when you print it to see the result, enumeration in the first column is not a part of the dataframe so don't worry. Also, "level_0", "level_1", "0" in the first row are just column names

Good luck!

Upvotes: 1

Related Questions