2016-11-09 83 views
1

我得到这个数据帧替换数据帧值:与熊猫

   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] 

但我不知道是否是最高效的方式。

+0

试试这个'df.Item = df。 Item.str.replace('\([^ \)] * \)','')' – MaxU

回答

2

该做的伎俩:

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

您可以通过regexstr.strip如果需要删除最后空格使用str.replace

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

另一个simplier解决方案与str.splitindexing with str

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