Search code examples
pythonpandasmelt

How to transpose and autofill a dataframe with python?


I have a dataframe like below:

NaN    1/1/2018    2/1/2018
item1    1    2
item2    3    4

I would like to transform the dataframe to make it look like this:

Date    Item    Price
1/1/2018    item1    1
1/1/2018    item2    3
2/1/2018    item1    2
2/1/2018    item2    4

I have tried df.pivot and df.t but neither works. Any suggestions or hints are very much appreciated!

Thanks!


Solution

  • You can use pd.melt like so:

    pd.melt(DF, id_vars=['NaN'], var_name='Date', value_name='Price')
    
         NaN      Date  Price
    0  item1  1/1/2018      1
    1  item2  1/1/2018      3
    2  item1  2/1/2018      2
    3  item2  2/1/2018      4