Home > Mobile >  How to swap Dataframe elements in python?
How to swap Dataframe elements in python?

Time:03-11

I have sample dataframe DF1:

A B C 
1 X Y
2 I J

and I would like to swap the dataframe like this :

A
1.B X
1.C Y
2.B I
2.C J

I tried using iloc and loc but its not working as expected.

Thanks for your time :)

CodePudding user response:

df.melt is perfect for this:

new_df = df.melt(id_vars='A').sort_values('A')

Output:

>>> new_df
   A variable value
0  1        B     X
2  1        C     Y
1  2        B     I
3  2        C     J

With formatting:

new_df = df.melt(id_vars='A').sort_values('A').apply(lambda row: f'{row.A}.{row.variable} {row.value}', axis=1).to_frame('A')

Output:

>>> new_df
       A
0  1.B X
2  1.C Y
1  2.B I
3  2.C J

CodePudding user response:

set index and stack

 df.set_index('A').stack()

A   
1  B    X
   C    Y
2  B    I
   C    J
  • Related