Gingerbread
Gingerbread

Reputation: 2122

converting unstacked dataframe into a dataframe in pandas

I have a dataframe like the following:

This dataframe is a result of unstacking another dataframe.

cost                 10        20        30
-------------------------------------------
cycles
--------------------------------------------
1                     2         4         6
2                     1         2         3
3                     3         6         9
4                     1         0         5

I want something like this:

cycles                10        20        30
-----------------------------------------------
1                     2         4         6
2                     1         2         3
3                     3         6         9
4                     1         0         5

I am a little confused about pivoting in the unstacked dataframes. I went through a couple of other similar posts but I really couldn't understand. I want to perform regression on every column of this dataframe. I figured it would be difficult to access the cycles column in the first dataframe, so I would really appreciate if someone can shed any light on this. Thanks in advance!

Upvotes: 1

Views: 971

Answers (1)

James
James

Reputation: 36691

Do you want this?

df.reset_index()

Edit: To drop the axis name cost, you need to use:

df.rename_axis(None, axis=1).reset_index()

This will still return an index, that is just the way pandas works, but it will not have a label floating over it. If you want cycle as the index without cost, you can just use the first part:

df.rename_axis(None, axis=1)

Upvotes: 2

Related Questions