Skip to main content
 首页 » 编程设计

python之通过跳过缺失值 Python 3 有效地迭代字典列表值

2025年05月04日8qq78292959

我有一个 Pandas 数据框

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这是唯一的方法吗?

请您参考如下方法:

简单的 continue 没有错。

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

有点跑题了:

& (df.Tag1 == '') 是多余的。仅当您的值有巧合时,我才有用,但这会导致不可预测的行为,因为 dict 没有排序。