1

I get this data frame:

               Item ................. 
0              Banana (From Spain)... 
1              Chocolate ............ 
2              Apple (From USA) ..... 
               ............

And I want change all Item's names by removing the parenthesis, getting finally

               Item ................. 
0              Banana ............... 
1              Chocolate ............ 
2              Apple ................ 
               ............

I thought, I should use replace but there are too much data so I'm thinking in use something like

import re

    for i in dataframe.index:
       if bool(re.search('.*\(.*\).*', dataframe.iloc[i]["Item"])):
          dataframe.ix[i,"Item"] = dataframe.iloc[i]["Item"].split(" (")[0]

But I'm not sure if is the most efficient way.

1
  • try this df.Item = df.Item.str.replace('\([^\)]*\)', '') Commented Nov 9, 2016 at 14:11

2 Answers 2

2

This does the trick:

df.Item = df.Item.apply(lambda x: x.split(" (")[0])
Sign up to request clarification or add additional context in comments.

Comments

2

You can use str.replace by regex with str.strip if need remove last whitespaces:

df.Item = df.Item.str.replace(r"\(.*\)","").str.strip()
print (df)
        Item
0     Banana
1  Chocolate
2      Apple

Another simplier solution with str.split with indexing with str:

df.Item = df.Item.str.split(' \(').str[0]
print (df)
        Item
0     Banana
1  Chocolate
2      Apple

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.