replace part of the string in pandas data frame
To add to @jezrael's answer, you need to include regex=True
otherwise it would match directly. Also, here it replaces the values across all columns in the data frame. If you don't intend this, you could filter to a column and then replace. For replacing across all values in the data frame, try:
df.replace('HF', 'Hi Funny', regex=True)
You could also provide a list based patterns and replacement values. The complete set of options are provided in the documentation here.
So if the data frame is:
>df = pd.DataFrame({'Column': ['HF - Antartica', 'HF - America', 'HF - Asia']})
>df.replace('HF', 'Hi Funny', regex=True)
should print:
Column
0 Hi Funny - Antartica
1 Hi Funny - America
2 Hi Funny - Asia
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