Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas – how to swap first two elements in a multi-value column

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(.*)’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading