pythonpandas

replace part of the string in pandas data frame


I have a pandas data frame in which I need to replace one part of the string value with another string value:

For example, I have:

HF - Antartica
HF - America
HF - Asia

Out of which I'd like to replace ony the HF - part, thus the result should be:

Hi Funny Antartica
Hi Funny America
Hi Funny Asia

I have tried pd.replace() but it doesn't work as I need only one part of the string replaced, rather than the entire string.


Solution

  • It seems you need Series.replace:

    print (df)
                  val
    0  HF - Antartica
    1    HF - America
    2       HF - Asia
    
    print (df.val.replace({'HF -':'Hi'}, regex=True))
    0    Hi Antartica
    1      Hi America
    2         Hi Asia
    Name: val, dtype: object
    

    Similar solution with str.replace:

    print (df.val.str.replace('HF -', 'Hi'))
    0    Hi Antartica
    1      Hi America
    2         Hi Asia
    Name: val, dtype: object