3

I need to extract only the content inside the brackets in pandas dataframe. I tried using str.exratct() but its not working . I need help with the extraction

DATA: ( IS IN DATA FRAME, This is a sample data from one row )

By:Chen TX (Chen Tianxu)[ 1 ] ; Tribbitt MA (Tribbitt Mark A.)[ 2 ] ; Yang Y (Yang Yi)[ 3 ] ; Li XM (Li Xiaomei)[ 4 ]

1 Answers1

3

You can use the regular expression:

import pandas as pd
import re

dataset = pd.DataFrame([{'DATA': 'By:Chen TX (Chen Tianxu)[ 1 ] ; Tribbitt MA (Tribbitt Mark A.)[ 2 ] ; Yang Y (Yang Yi)[ 3 ] ; Li XM (Li Xiaomei)[ 4 ]'}])
print(dataset)

Dataframe is:

   DATA
0  By:Chen TX (Chen Tianxu)[ 1 ] ; Tribbitt MA (Tribbitt Mark A.)[ 2 ] ; Yang Y (Yang Yi)[ 3 ] ; Li XM (Li Xiaomei)[ 4 ]

Then, using regular expression with lambda function, such that you extract names and save it to different column named names:

# regular expression from: https://stackoverflow.com/a/31343831/5916727
dataset['names'] = dataset['DATA'].apply(lambda x: re.findall('\((.*?)\)',x))
print(dataset['names'])

Output of names column would be:

0    [Chen Tianxu, Tribbitt Mark A., Yang Yi, Li Xiaomei]
niraj
  • 17,498
  • 4
  • 33
  • 48
  • 1
    @venkatesh_Babu Great! you can accept the answer if you would like. `Happy Coding.` – niraj Jun 26 '17 at 03:14
  • but how do remove the [ ] ?? can you pleased help me out . tried replace function but it didnt work – venkatesh_Babu Jun 26 '17 at 03:16
  • you mean you want `Chen Tianxu, Tribbitt Mark A., Yang Yi, Li Xiaomei` as single string, because right now it is list of string separated with `,` – niraj Jun 26 '17 at 03:17