Regex finding word next to a key word in Pandas column and replace few characters

Viewed 55

I have a dataframe which looks like as below

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
           'B': ['a is host 0itdsiekivnme0itdxm', 'mmm pc is host sesoltsm09sds', 'winter on is host sesdfdfdf9', 'd is host SESCPIWM1344 sdfds asd', 'check my host sesdfdsm1dsdd0 friendly']})

I am trying to find the word after 'host' and replace the first two character with xx

like below

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
               'B': ['a is host xxtdsiekivnme0itdxm', 'mmm pc is host xxsoltsm09sds', 'winter on is host xxsdfdfdf9', 'd is host xxSCPIWM1344 sdfds asd', 'check my host xxsdfdsm1dsdd0 friendly']})

I tried following, but it doesn't work

df['spc3'] = df['B'].str.replace('(?<=host)(\w{2})', r'\1xx')
2 Answers

This will work if the word after "host" comes after a single space.

df['spc3'] = df['B'].str.replace('(?<=host )\w{2}', 'xx')

Output:

   A  ...                                   spc3
0  0  ...          a is host xxtdsiekivnme0itdxm
1  1  ...           mmm pc is host xxsoltsm09sds
2  2  ...           winter on is host xxsdfdfdf9
3  3  ...       d is host xxSCPIWM1344 sdfds asd
4  4  ...  check my host xxsdfdsm1dsdd0 friendly

if the word after "host" comes after a single space. If this is not true always let me know.

Your regex is almost there, but you need to modify your capture group to (\s+) so you only capture the spaces after host.

Leave the \w{2} outside the capture parentheses -- if you put \w{2} inside the parentheses, then you include those 2 characters in the capture group and then put them right back as part of \1.

df['B'].str.replace('(?<=host)(\s+)\w{2}', r'\1xx')
                              ^^^^^

#    A  B
# 0  0  a is host xxtdsiekivnme0itdxm
# 1  1  mmm pc is host xxsoltsm09sds
# 2  2  winter on is host xxsdfdfdf9
# 3  3  d is host xxSCPIWM1344 sdfds asd
# 4  4  check my host xxsdfdsm1dsdd0 friendly
Related