0

right now I'm dealing with a dataframe like this:

Old dataframe:

name    |    place    |    val_a_1    |    val_a_2    |    val_b_1    |    val_b_2
name_a  |    place_a  |    17         |    42         |    1          |    3
name_b  |    place_b  |    82         |    109        |    44         |    13
...

Is there a specific function inside pandas to change the format of the dataframe and split every row into multiples, like this:

New dataframe:

name    |    place    |    val_a    |    val_b
name_a  |    place_a  |    17       |    1
name_a  |    place_a  |    1        |    3
name_b  |    place_b  |    82       |    44
name_b  |    place_b  |    109      |    13
...

As you can see, I always have multiple pairs of data: val_a_1 & val_b_1, val_a_2 & val_b_2, and so on...

Thanks for your help and have a great day!

finethen
  • 385
  • 1
  • 4
  • 19

1 Answers1

2

Use wide_to_long:

df = (pd.wide_to_long(df, 
                      stubnames=['val_a','val_b'], 
                      i=['name','place'], 
                      j='i', 
                      sep='_').droplevel(-1).reset_index())
print (df)
     name    place  val_a  val_b
0  name_a  place_a     17      1
1  name_a  place_a     42      3
2  name_b  place_b     82     44
3  name_b  place_b    109     13
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252