2015-04-26 24 views
2

遍歷字典列表值我有一個熊貓數據幀有效地跳過缺失值的Python 3

import pandas as pd 

df=pd.DataFrame({'Location': [ 'NY', 'SF', 'NY', 'NY', 'SF', 'SF', 'TX', 'TX', 'TX', 'DC'], 
       'Class': ['H','L','H','L','L','H', 'H','L','L','M'], 
       'Address': ['12 Silver','10 Fak','12 Silver','1 North','10 Fak','2 Fake', '1 Red','1 Dog','2 Fake','1 White'], 
       'Score':['4','5','3','2','1','5','4','3','2','1',]}) 

而且我要補充,我存儲在字典2個標籤。需要注意的是,第二字典不包括關鍵的「A」

df['Tag1'] ='' 
df['Tag2'] ='' 

tagset1 = {'A':['NY|SF'], 
      'B':['DC'], 
      'C':['TX'], 
      } 
for key in tagset1: 
    df.loc[df.Location.str.contains(tagset1[key][0]) & (df.Tag1 == ''),'Tag1'] = key 


tagset2= {'B':['H|M'], 
      'C':['L'], 
      } 
for key in tagset2: 
    df.loc[df.Class.str.contains(tagset2[key][0]) & (df.Tag2 == ''),'Tag2'] = key 

print (df) 

如果我想將兩個字典相結合,使代碼更易讀,高效的,我應該填寫在newtagset['A'][1]當場A和''還是有在迭代列表中的位置時,使迭代器忽略或跳過位置newtagset['A'][1]的另一種方法是什麼?

newtagset = {'A':['NY|SF', '',], 
      'B':['DC','H|M',], 
      'C':['TX','L',], 
      } 


for key in newtagset: 
    df.loc[df.Location.str.contains(newtagset[key][0]) & (df.Tag1 == ''),'Tag1'] = key 

for key in newtagset: 
    df.loc[df.Class.str.contains(newtagset[key][1]) & (df.Tag2 == ''),'Tag2'] = key 

print (df) 

我找到的大多數解決方案都使用itertools Skip multiple iterations in loop python這是唯一的方法嗎?

回答

1

簡單的continue沒有錯。

for key, value in newtagset.items(): # I found dict.items cleaner 
    if not value[1]: 
     continue 
    df.loc... 

題外話的位:

& (df.Tag1 == '')是多餘的。只有當你在價值觀上有巧合時,我纔會有用,但這會導致不可預知的行爲,因爲字典沒有排序。