Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

only remove integers within bracket from df column – pandas

I’m trying to remove brackets with integers only from a df column. If it’s an object than I’m hoping to keep it. Using below, there are certain rows that have two brackets. I only want to remove brackets that are all integers.

df = pd.DataFrame({
'col': ['Bear  (123)', 'Dog (No 2a)  (1502)', 'Cat Dog (No 7b)  (16772)', 'Bear  (123)']})

df['col'] = df['col'].str.replace(r"\(.*\)","")

intended out:

               col
0             Bear  
1      Dog (No 2a)
2  Cat Dog (No 7b)
3             Bear  

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use:

df['col'] = df['col'].str.replace(r'\s*\(\d*\)', '', regex=True)

output:

               col
0             Bear
1      Dog (No 2a)
2  Cat Dog (No 7b)
3             Bear

regex demo

\s*    # match spaces (optional)
\(     # match literal (
\d*    # match zero or more digits (use \d+ to force at least 1 digit)
\)     # match literal )

NB. use regex=True to avoid the future warning.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading