2016-07-29 73 views
-1

因此,這裏是我的代碼根據「位置」列的拆分值條件更新許多列值。該代碼工作正常,但由於它的行迭代它不夠高效。任何人都可以幫助我使代碼更快運行嗎?根據其中一列的分隔值高效地更新列

for index, row in df.iterrows(): 
    print index 
    location_split =row['location'].split(':') 
    after_county=False 
    after_province=False 
    for l in location_split: 

     if l.strip().endswith('ED'): 
      df[index, 'electoral_district'] = l 

     elif l.strip().startswith('County'): 
      df[index, 'county'] = l 
      after_county = True 

     elif after_province ==True: 
      if l.strip()!='Ireland': 
       df[index, 'dublin_postal_district'] = l 

     elif after_county==True: 
      df[index, 'province'] = l.strip() 
      after_province = True 

回答

0

'地圖' 是我需要的東西:)

def fill_county(column): 
    res = '' 
    location_split = column.split(':') 

    for l in location_split: 
     if l.strip().startswith('County'): 
      res= l.strip() 
      break 
    return res 

df['county'] = map(fill_county, df['location'])