0

I have the following pandas dataframe: enter image description here

I want to change this dataframe in the following way: I want to have the ID column as index and the month for each index in a column named month, and then all the values as follow:

ID    MONTH  VAL
1     Jan    nan
1     Feb    nan
1     Mar    nan
1     Apr    nan
1     May    nan
1     Jun    nan
1     Jul    nan
1     Aug    94.0000
1     Sep    113.0000
1     Oct    21.0000
1     Nov    nan
2     Jan    107.00000
.
.
.
7     Nov    nan

The order of the month is not important. Is there an easy way to do it?

Marco
  • 1,195
  • 3
  • 18
  • 30
  • 3
    Instead of posting a picture, can you post output from `df.head(10).to_dict()`. This will help us test solutions. – jpp Feb 21 '18 at 22:08

1 Answers1

1

Try stack with dropnaparameter set to False:

df.set_index('ID').stack(dropna=False)

@PaulH is correct in his observations from the comments below.

To move that column index to row index converting from a wide dataframe to a long dataframe.

Scott Boston
  • 147,308
  • 15
  • 139
  • 187