I have pandas data frame in which I need to replace one part of the vale with another value
for Example. I have
JavaScript
x
4
1
HF - Antartica
2
HF - America
3
HF - Asia
4
out of which I’d like to replace ony the HF -
part
thus the result would be
JavaScript
1
4
1
Hi Funny Antartica
2
Hi Funny America
3
Hi Funny Asia
4
I have tried pd.replace()
but it doesnt work as I need only one part of the string replaced, rather than the entire string
Advertisement
Answer
It seems you need Series.replace
:
JavaScript
1
12
12
1
print (df)
2
val
3
0 HF - Antartica
4
1 HF - America
5
2 HF - Asia
6
7
print (df.val.replace({'HF -':'Hi'}, regex=True))
8
0 Hi Antartica
9
1 Hi America
10
2 Hi Asia
11
Name: val, dtype: object
12
Similar solution with str.replace
:
JavaScript
1
6
1
print (df.val.str.replace('HF -', 'Hi'))
2
0 Hi Antartica
3
1 Hi America
4
2 Hi Asia
5
Name: val, dtype: object
6