Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas wide format transpose to long format

Tags:

python

pandas

I have a pandas dataframe like this, with an ID column and a bunch of indicator columns(True/False):

df_have:

ID Male  Special_Need    Teeanger
1    T      F              T
2    F      T              F

I want to transpose it but only for attributes = True. i.e.

df_want:

ID  Attribute
1    Male
1    Teenager
2   Special_Need
like image 519
Victor Avatar asked Nov 30 '25 02:11

Victor


2 Answers

Using stack

df.set_index('ID').rename_axis('Attribute',1).stack().loc[lambda x : x=='T'].reset_index().drop(0,1)
Out[268]: 
   ID     Attribute
0   1          Male
1   1      Teeanger
2   2  Special_Need
like image 105
BENY Avatar answered Dec 02 '25 17:12

BENY


Using melt:

u = df.melt(id_vars='ID', var_name='Attribute')
u.loc[u.value.eq('T'), ['ID', 'Attribute']]

   ID     Attribute
0   1          Male
3   2  Special_Need
4   1      Teeanger
like image 30
user3483203 Avatar answered Dec 02 '25 15:12

user3483203



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!