Home > Blockchain >  Replace and rearrange string value containing similar pattern of words
Replace and rearrange string value containing similar pattern of words

Time:11-23

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

CodePudding user response:

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

Output:

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