Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string and remove it from extracted column, pandas

Tags:

python

pandas

import pandas as pd
df=pd.DataFrame({'A':['my text your text']})

I want to extract part of string in column A which is my text to column B and remove it from A after extract.

First thing that I will do in that case is propably create B column and after that subtract B from A, but is there any better solution to do that?

df['B']=df['A'].str.extract('(my text)') 
df
                   A        B
0  my text your text  my text

Expected output:

             A        B
0    your text  my text

1 Answers

Use Series.str.replace with \s* for remove trailing whitespaces and n=1 for replace only first match:

df['B']=df['A'].str.extract('(my text)') 
df['A']=df['A'].str.replace('\s*(my text)\s*','', n=1)
print (df)
            A        B
0   your text  my text
like image 190
jezrael Avatar answered Sep 02 '25 17:09

jezrael