Home > Software engineering >  How to transform a Pandas DataFrame into the following display? (from horizontal to vertical; with r
How to transform a Pandas DataFrame into the following display? (from horizontal to vertical; with r

Time:10-13

data = {
    'Column 1': ['A', 'B'],
    'Column 2': ['a_base', 'b_base'],
    'Column 3': ['a_part', 'b_part']
}

df = pd.DataFrame(data)

Gives an output of:

Column 1 | Column 2 | Column 3 
A        | a_base   | a_part   
B        | b_base   | b_part 

How can I get the following:

New Column 1 | New Column 2 
A            | a_base       
A            | a_part       
B            | b_part       
B            | b_part       

CodePudding user response:

You can melt columns 2 and 3 into a new column, then select and sort by the columns you want to keep.

import pandas as pd

data = {
    'Column 1': ['A', 'B'],
    'Column 2': ['a_base', 'b_base'],
    'Column 3': ['a_part', 'b_part']
}

df = pd.DataFrame(data)

df2 = df.melt(id_vars=['Column 1'], value_vars=['Column 2', 'Column 3'], value_name='New Column 2')
df2 = df2[['Column 1', 'New Column 2']].sort_values(by='Column 1')
print(df2)

Output:

  Column 1 New Column 2
0        A       a_base
2        A       a_part
1        B       b_base
3        B       b_part
  • Related