Skip to content
Advertisement

Trying to stack several groups of columns into multiple target columns by name

I have the original dataframe like that which contains 1772 columns and 130 rows. I would like to stack them into multiple target columns.

id AA_F1R1 BB_F1R1 AA_F1R2 BB_F1R2 AA_F2R1 BB_F2R2 AA_F7R25 BB_F7R25
001 5 xy xx xx zy 1 4 xx
002 6 zzz yyy zzz xw 2 zzz 3 zzz

I found two different solutions that seem to work but for me is giving an error. Not sure if they work with NaN values.

JavaScript

Another solution I tried was

JavaScript

the problem with this last one is I couldn’t keep the columns I wanted.

I appreciate any inputs!

Advertisement

Answer

Use suffix=r'w+' parameter in wide_to_long:

JavaScript

In second solution add dropna=False to DataFrame.stack:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement