how to create a row for each corresponding column

Question:

I have a data frame which formatted like this:

Name 0 1 2 3
0 John object 1 object 2 Object 3 object 4
1 Smith object 1 object 2 Object 3 object 4
2 Jack object 1 object 2 Object 3 object 4

and I want to transform it to the following:

Name 0
0 John object1
1 John object2
2 John object3
3 John object4
4 Smith object1
5 Smith object2
6 Smith object3
7 Smith object4
8 Jack object1
9 Jack object2
10 Jack object3
11 Jack object4
Asked By: user14696236

||

Answers:

You could try:

import pandas as pd
import numpy as np

df = (pd.melt(df, id_vars=['Name'], value_vars=df.columns[1:])
 .drop(columns=['variable'])
 .sort_values(by='Name')
 .pipe(lambda g: g.set_axis(np.arange(0, len(g.index)), axis=0)))

df

     Name     value
0    Jack  object 1
1    Jack  object 2
2    Jack  Object 3
3    Jack  object 4
4    John  object 1
5    John  object 2
6    John  Object 3
7    John  object 4
8   Smith  object 1
9   Smith  object 2
10  Smith  Object 3
11  Smith  object 4
Answered By: Anoushiravan R
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.