【发布时间】:2015-07-04 16:35:54
【问题描述】:
我有一个熊猫数据框
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 的位置,还是有其他方法可以让迭代器忽略或跳过位置 @987654326 @ 迭代列表中的位置时?
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 这是唯一的方法吗?
【问题讨论】:
标签: python dictionary iteration