data-monkey
data-monkey

Reputation: 1715

Remove prefix with special characters in Python Pandas Series

How do I remove the Bale + Damon - prefix in the series below?

import pandas as pd
x = pd.Series(['Bale + Damon - Le Mans 66', 'Bale + Damon - Ford', 'Bale + Damon - vs.', 'Bale + Damon - Ferrari'])
print(x)
0    Bale + Damon - Le Mans 66
1    Bale + Damon - Ford
2    Bale + Damon - vs.
3    Bale + Damon - Ferrari

Desired output:

print(x2)
0    Le Mans 66
1    Ford
2    vs.
3    Ferrari

I have tried x2 = x.str.replace('Bale + Damon - ',''), but it doesn't alter the original series.

Upvotes: 0

Views: 146

Answers (2)

ansev
ansev

Reputation: 30930

We can also use Series.str.partition

x.str.partition(' - ').iloc[:,-1]
0    Le Mans 66
1          Ford
2           vs.
3       Ferrari
Name: 2, dtype: object

UPDATE

Series.str.replace with regex=False

x = x.str.replace('Bale + Damon - ','',regex=False)

#0    Le Mans 66
#1          Ford
#2           vs.
#3       Ferrari
#dtype: object

Upvotes: 0

BENY
BENY

Reputation: 323316

In your case

x.str.split(' - ',n=1).str[-1]   

0    Le Mans 66
1          Ford
2           vs.
3       Ferrari
dtype: object

Upvotes: 1

Related Questions