简体   繁体   中英

How to swap Dataframe elements in python?

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:)

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

set index and stack

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

A   
1  B    X
   C    Y
2  B    I
   C    J

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM