Replace and rearrange string value containing similar pattern of words

I am working in google collaboratory and I have a panda dataframe like below

Company name            Address
Meditera, PT            Street 1
Ocean express, PT       Street 2

I want to change to be like below :

Company name            Address
PT Meditera            Street 1
PT Ocean express       Street 2

The way I do now is using df['Company name'].str.replace('Meditera, PT','PT Meditera'). The data is growing each day and it will be so exhaustive to replace one by one. The pattern of the data is the same, I only need to rearrange ', PT' from behind to the front of company name.

Is there any suggestion how we can do this in smarter way so that I do not need to manually use str.replace() every day.

Thanks before

1 answer

  • answered 2021-11-23 01:55 user17242583

    df['Company name'] = df['Company name'].str.split(', ').str[::-1].str.join(' ')


    >>> df
           Company name   Address
    0       PT Meditera  Street 1
    1  PT Ocean express  Street 2

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum