2016-11-09 98 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