'Python, Pandas: changing form of dataframe, one-to-multiple-columns [duplicate]
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!
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
