简体   繁体   中英

PANDAS : move a part of a sub-string to the end of the string based on condition

I have a data-frame:

df1 = pd.DataFrame({'Title': ['WAW_WELCOME AIRPORT-Q3-2022 Facility', 'GVA_NEWREST INFLIGHT-Q3-2022 Cleaning', 'AGP_RENTEVIC-Q3-2022 Office']})

I would like to move a substring that is between the first "_" and the first "-" to the end of the string and separate it with a "/".

So the result would be:

在此处输入图像描述

You can use:

after = df1['Title'].str.split('_', 1)
before = after.str[1].str.split('-', 1)

df1['new'] = after.str[0] + '-' + before.str[1] + '/' + before.str[0]

OUTPUT

    Title                                    new
0   WAW_WELCOME AIRPORT-Q3-2022 Facility   WAW-Q3-2022 Facility/WELCOME AIRPORT
1  GVA_NEWREST INFLIGHT-Q3-2022 Cleaning  GVA-Q3-2022 Cleaning/NEWREST INFLIGHT
2            AGP_RENTEVIC-Q3-2022 Office            AGP-Q3-2022 Office/RENTEVIC

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