Efficiently Iterating over dictionary list values by skipping missing values Python 3 -
i have pandas dataframe
import pandas 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',]})
and want add 2 tags stored in dictionaries. note second dictionary not include key 'a'
df['tag1'] ='' df['tag2'] ='' tagset1 = {'a':['ny|sf'], 'b':['dc'], 'c':['tx'], } key in tagset1: df.loc[df.location.str.contains(tagset1[key][0]) & (df.tag1 == ''),'tag1'] = key tagset2= {'b':['h|m'], 'c':['l'], } key in tagset2: df.loc[df.class.str.contains(tagset2[key][0]) & (df.tag2 == ''),'tag2'] = key print (df)
if want combine both dictionaries make code more readable , efficient should fill in spot in newtagset['a'][1]
''
or there way make iterator ignore or skip position newtagset['a'][1]
when iterating on position in list?
newtagset = {'a':['ny|sf', '',], 'b':['dc','h|m',], 'c':['tx','l',], } key in newtagset: df.loc[df.location.str.contains(newtagset[key][0]) & (df.tag1 == ''),'tag1'] = key key in newtagset: df.loc[df.class.str.contains(newtagset[key][1]) & (df.tag2 == ''),'tag2'] = key print (df)
most solutions found uses itertools skip multiple iterations in loop python way?
there nothing wrong simple continue
.
for key, value in newtagset.items(): # found dict.items cleaner if not value[1]: continue df.loc...
a bit of off topic:
& (df.tag1 == '')
redundant. useful if had coincidences in values, lead unpredictable behavior, since dict not ordered.
Comments
Post a Comment