Skip to content Skip to sidebar Skip to footer

Pandas Series Replace Using Dictionary With Regex Keys

Suppose there is a dataframe defined as df = pd.DataFrame({'Col_1': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '0'], 'Col_2': ['a', 'b', 'c', 'd', 'e',

Solution 1:

Use anchors (^ and $, that is):

repl_dict = {re.compile('^[ABH-LP-Z]$'): 'DDD',
             re.compile('^[CDEFG]$'): 'BBB WTT',
             re.compile('^[MNO]$'): 'AAA WTT',
             re.compile('^[0-9]+$'): 'CCC'}

Which produces with df['Col_1'].replace(repl_dict, regex=True):

0         DDD
1         DDD
2     BBB WTT
3     BBB WTT
4     BBB WTT
5     BBB WTT
6     BBB WTT
7         DDD
8         DDD
9         DDD
10        CCC

Post a Comment for "Pandas Series Replace Using Dictionary With Regex Keys"