【发布时间】:2016-05-29 01:21:36
【问题描述】:
我有一个数据框:
df = pd.DataFrame({'id' : ['abarth 1.4 a','abarth 1 a','land rover 1.3 r','land rover 2',
'land rover 5 g','mazda 4.55 bl'],
'series': ['a','a','r','','g', 'bl'] })
我想从对应的id中删除'series'字符串,所以最终结果应该是:
'id': ['abarth 1.4','abarth 1','land rover 1.3','land rover 2','land rover 5', 'mazda 4.55']
目前我正在使用 df.apply:
df.id = df.apply(lambda x: x['id'].replace(x['series'], ''), axis =1)
但这会删除字符串的所有实例,换句话说,就像这样:
'id': ['brth 1.4','brth 1','land ove 1.3','land rover 2','land rover 5', 'mazda 4.55']
我是否应该像这样将正则表达式与 df.apply 中的变量混合匹配?
df.id = df.apply(lambda x: x['id'].replace(r'\b' + x['series'], ''), axis =1)
【问题讨论】: