1

I have my input dataframe like this:

df = pd.DataFrame({
    'X' : [1],
    'Y' : [2],
    'Z' : [3],
    'A_col1' : [10],
    'A_col2' : [20],
    'B_col1' : [100],
    'B_col2' : [200],
})

enter image description here

How do I convert it into the below format?

final_df = pd.DataFrame({
    'X' : [1,1],
    'Y' : [2,2],
    'X' : [3,3],
    'Name' : ['A','B'],
    'col1' : [10,20],
    'col2' : [100,200]
})

enter image description here

Any help is appreciated

AswinRajaram
  • 1,519
  • 7
  • 18
  • 2
    Use `df1 = df.set_index(['X','Y', 'Z'])` `df1.columns = df1.columns.str.split('_', expand=True)` `df1 = df1.rename_axis(['Name',None], axis=1).stack(0).reset_index()` – jezrael Feb 12 '21 at 06:15

0 Answers0