Home > Software design >  pandas - how to swap first two elements in a multi-value column
pandas - how to swap first two elements in a multi-value column

Time:11-30

I have below data

SFDC,CMN,CMID,SID,MID,C_PG,ACT DCA,customer1,company1,SID1,cherie,cherie,"view_page_modulepicker,explore_more_connect with people" DCA,customer2,company2,SID2,cherie,cherie,"view_manage_opportunities,view_page_modulepicker,back_to_opp,view_page_modulepicker" DCA,customer1,company1,SID1,cherie,cherie,"view_manage_opportunities,view_page_modulepicker,explore_more_connect with people" DCA,customer1,company1,SID1,cherie,cherie,"view_page_modulepicker" DCA,customer1,company1,SID1,cherie,cherie,"view_manage_opportunities" DCA,customer4,company1,SID4,cherie,cherie,"view_manage_opportunities,view_page_actionSource" DCA,customer4,company1,SID4,cherie,cherie,"view_manage_opportunities,view_page_homePage" DCA,customer4,company1,SID4,cherie,cherie,"view_manage_opportunities,view_page_capabilities" ...... ......

Now i want to find the rows that first element in ACT column is 'view_manage_opportunities', and second element in ACT column is 'view_page(.*)'

then swap these two elements . so the expected output is

SFDC,CMN,CMID,SID,MID,C_PG,ACT DCA,customer1,company1,SID1,cherie,cherie,"view_page_modulepicker,explore_more_connect with people" DCA,customer2,company2,SID2,cherie,cherie,"view_page_modulepicker,view_manage_opportunities,back_to_opp,view_page_modulepicker" DCA,customer1,company1,SID1,cherie,cherie,"view_page_modulepicker,view_manage_opportunities,explore_more_connect with people" DCA,customer1,company1,SID1,cherie,cherie,"view_page_modulepicker" DCA,customer1,company1,SID1,cherie,cherie,"view_manage_opportunities" DCA,customer4,company1,SID4,cherie,cherie,"view_page_actionSource,view_manage_opportunities" DCA,customer4,company1,SID4,cherie,cherie,"view_page_homePage,view_manage_opportunities" DCA,customer4,company1,SID4,cherie,cherie,"view_page_capabilities,view_manage_opportunities" ...... ......

can any expert help on this requirement with pandas?

CodePudding user response:

You may use str.replace here:

df["ACT"] = df["ACT"].str.replace(r'(view_manage_opportunities),(view_page[^,]*)', r'\2,\1')

Check the regex demo here.

  • Related