python - Reshaping a pandas dataframe by repeating rows -


i new python pandas. have 1 dataframe

----------------------------------------------------- id     name    salary    desc1     desc2     desc3 ----------------------------------------------------- 1      abc1    2000       x1        y1        z1 ----------------------------------------------------- 2      abc2    5000       x2        y1        z2 ----------------------------------------------------- 

i want transform way

----------------------------------------- id     name     salary      variable ----------------------------------------- 1      abc1      2000          x1 ----------------------------------------- 1      abc1      2000          y1 ----------------------------------------- 1      abc1      2000          z1   ----------------------------------------- 2      abc2      5000          x2   ----------------------------------------- 2      abc2      5000          y2   ----------------------------------------- 2      abc2      5000          z2  ----------------------------------------- 

please help. in advance.

you need set_index + stack:

df = df.set_index(['id','name','salary'])        .stack()        .reset_index(level=3, drop=true)        .reset_index(name='variable')  print (df)    id  name  salary variable 0   1  abc1    2000       x1 1   1  abc1    2000       y1 2   1  abc1    2000       z1 3   2  abc2    5000       x2 4   2  abc2    5000       y1 5   2  abc2    5000       z2 

if sorting first 3 columns not necessary:

use melt:

df = df.melt(['id','name','salary'], value_name='variable').drop('variable', axis=1) print (df)    id  name  salary variable 0   1  abc1    2000       x1 1   2  abc2    5000       x2 2   1  abc1    2000       y1 3   2  abc2    5000       y1 4   1  abc1    2000       z1 5   2  abc2    5000       z2 

lreshape undocumented, possible in future removed (github link).

df = pd.lreshape(df, {'variable':['desc1','desc2','desc3']}) print (df)    id  name  salary variable 0   1  abc1    2000       x1 1   2  abc2    5000       x2 2   1  abc1    2000       y1 3   2  abc2    5000       y1 4   1  abc1    2000       z1 5   2  abc2    5000       z2 

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -