用 Pandas 替换数据框中的值

Replace values in data frame with Pandas

我得到这个数据框:

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

我想通过删除括号来更改所有项目的名称,最终得到

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

我想,我应该使用替换,但数据太多,所以我正在考虑使用类似

的东西
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]

但我不确定这是不是最有效的方法。

如果需要删除最后的空格,您可以使用 str.replace by regex with str.strip

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

另一个更简单的解决方案str.split with indexing with str

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

这样就可以了:

df.Item = df.Item.apply(lambda x: x.split(" (")[0])