How can I remove the incomplete parenthesis without affect other row using pandas?

Viewed 33

I have a data frame where I want to remove the parentheses and the string without affecting other row.

Assume the following dataframe "cusomter" with the column "Name"

Name
Company ABC (Malaysia) Ltd
Company HIJ (M) Ltd (B12
Company KLM (M) Ltd (

My code:

customer["Name"] = customer["Name"].str.replace(r"\([^()]{1,3}", "", regex=True)

Output:

Name
Company ABC aysia) Ltd
Company HIJ (M) Ltd
Company KLM (M) Ltd

My desire output:

Name
Company ABC (Malaysia) Ltd
Company HIJ (M) Ltd
Company KLM (M) Ltd

May I know if is it possible to do it? I had tried different codes and I'm still not able to get my desired output.

1 Answers

Assuming there won't be nested parentheses in the garbage section, you can anchor the replacement to the end of the string.

import pandas as pd

df = pd.DataFrame({"company": ["Company ABC (Malaysia) Ltd", "Company HIJ (M) Ltd (B12", "Company KLM (M) Ltd ("]})

df["company"] = df["company"].str.replace(r"\s*\([^()]*?$", "", regex=True)

print(df)
                      company
0  Company ABC (Malaysia) Ltd
1         Company HIJ (M) Ltd
2         Company KLM (M) Ltd
Related