Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas melt multiple groups into single column

Original DataFrame:

+----+----------+----------+----------+----------+
| ID |  var1hrs |  var2hrs |  ind1var |  ind2var |
+----+----------+----------+----------+----------+
|  1 |       55 |       45 |      123 |      456 |
|  2 |       48 |       60 |      331 |      222 |
+----+----------+----------+----------+----------+

Target DataFrame:

+----+------------+------+------+
| ID |    type    |  hrs |  ind |
+----+------------+------+------+
|  1 |  primary   |   55 |  123 |
|  1 |  secondary |   45 |  456 |
|  2 |  primary   |   48 |  331 |
|  2 |  secondary |   60 |  222 |
+----+------------+------+------+

How would I go about melting multiple groups of variables into a single label column? The "1" in the variable names indicate type = "primary" and "2" indicates type = "secondary".

like image 491
jerbear Avatar asked Nov 26 '25 13:11

jerbear


1 Answers

After modify the columns' name, we can using wide_to_long

df.columns=df.columns.str[:4]
s=pd.wide_to_long(df,['var','ind'],i='ID',j='type').reset_index()
s=s.assign(type=s.type.map({'1':'primary','2':'secondary'})).sort_values('ID')
s

   ID       type  var  ind
0   1    primary   55  123
2   1  secondary   45  456
1   2    primary   48  331
3   2  secondary   60  222
like image 120
BENY Avatar answered Nov 28 '25 03:11

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!