删除 Python Pandas 系列中带有特殊字符的前缀
Remove prefix with special characters in Python Pandas Series
如何删除以下系列中的 Bale + Damon -
前缀?
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
期望的输出:
print(x2)
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
我已经试过了x2 = x.str.replace('Bale + Damon - ','')
,但它并没有改变原来的系列。
你的情况
x.str.split(' - ',n=1).str[-1]
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
dtype: object
我们也可以用Series.str.partition
x.str.partition(' - ').iloc[:,-1]
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
Name: 2, dtype: object
更新
Series.str.replace
与 regex=False
x = x.str.replace('Bale + Damon - ','',regex=False)
#0 Le Mans 66
#1 Ford
#2 vs.
#3 Ferrari
#dtype: object
如何删除以下系列中的 Bale + Damon -
前缀?
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
期望的输出:
print(x2)
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
我已经试过了x2 = x.str.replace('Bale + Damon - ','')
,但它并没有改变原来的系列。
你的情况
x.str.split(' - ',n=1).str[-1]
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
dtype: object
我们也可以用Series.str.partition
x.str.partition(' - ').iloc[:,-1]
0 Le Mans 66
1 Ford
2 vs.
3 Ferrari
Name: 2, dtype: object
更新
Series.str.replace
与 regex=False
x = x.str.replace('Bale + Damon - ','',regex=False)
#0 Le Mans 66
#1 Ford
#2 vs.
#3 Ferrari
#dtype: object