regex - python pandas use map with regular expressions -
i have dict:
dealer = { 'esselunga': 'spesa', 'decathlon 00000120': 'sport', 'leroy merlin': 'casa', 'conad 8429': 'spesa', 'ikea': 'casa', 'f.lli madaffari': 'spesa', 'supermercato il gigant': 'spesa', 'naturasi spa': 'spesa', 'esselunga settimo milane': 'spesa' }
and want map pandas df:
entries.categoria = entries.commerciante.map(dealer)
is there way use regex match map on "commerciante" column? in way can rewrite dealer this:
dealer = { 'esselunga': 'spesa', 'decathlon': 'sport', 'leroy merlin': 'casa', 'conad': 'spesa', 'ikea': 'casa', 'f.lli madaffari': 'spesa', 'supermercato il gigant': 'spesa', 'naturasi spa': 'spesa', 'esselunga settimo milane': 'spesa' }
and match both "decathlon" , "decathlon 00000120"
thank of you. used suggestions resolve problem. defined new function:
def dealer_replace(dealer_dict, text): regex = re.compile("(%s)" % "|".join(map(re.escape, dealer_dict.keys()))) if regex.search(text): ret = regex.search(text) return dealer_dict[ret.group()] else: return none
and use apply
entries['categoria'] = entries['commerciante'].apply(lambda v: dealer_replace(dealer, str(v)))
Comments
Post a Comment