0

Hello, I need to create a new dataframe which has an index column created from three diffrent columns of the original dataframe.

  • The original dataframe (data) is:

    data = pd.DataFrame ({'DATE': ['Jan', 'Feb', 'Aug', 'Sep'], 'D1': ['12', '21', '32', '45'], 'D2': ['18', '22', '56', '12'], 'D3': ['13', '31', '82', '63']},index=[0, 1, 2, 3])

And it looks like this:

  DATE  D1  D2  D3
0  Jan  12  18  13
1  Feb  21  22  31
2  Aug  32  56  82
3  Sep  45  12  63
  • From this original dataframe my goal is to create a dataframe (data_ds), which has two indexes (DATE and Ds), and looks like this:

                Dvalues
    DATE Ds
    Jan  D1     12
         D2     18
         D3     13
    Feb  D1     21
         D2     22
         D3     31
    Aug  D1     32
         D2     56
         D3     82
    Sep  D1     45
         D2     12
         D3     63
    

I have tried the following code, but I don't get there:

import pandas as pd
import numpy as np

data = pd.DataFrame ({'DATE': ['Jan', 'Feb', 'Aug', 'Sep'],
                'D1': ['12', '21', '32', '45'],
                'D2': ['18', '22', '56', '12'],
                'D3': ['13', '31', '82', '63']},index=[0, 1, 2, 3])


data_d1 = data[['DATE','D1']].copy()
data_d1 = data_d1.set_index('DATE')

data_d2 = data[['DATE','D2']].copy()
data_d2 = data_d2.set_index('DATE')

data_d3 = data[['DATE','D3']].copy()
data_d3 = data_d3.set_index('DATE')

data_ds=pd.concat([data_d1,data_d2,data_d3])
datos_ds = data_ds.set_index('DATE',(D1,D2,D3)) 

Thank you

1 Answer 1

1

stack after set_index

data.set_index('DATE').stack().to_frame('Dvalues')
Out[99]: 
        Dvalues
DATE           
Jan  D1      12
     D2      18
     D3      13
Feb  D1      21
     D2      22
     D3      31
Aug  D1      32
     D2      56
     D3      82
Sep  D1      45
     D2      12
     D3      63
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.