pandas dataframe返回列的字符串中的第一个单词

Tes*_*ty8 5 python dataframe pandas

我有一个数据帧:

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'] })
Run Code Online (Sandbox Code Playgroud)

我想从相应的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)
Run Code Online (Sandbox Code Playgroud)

但这会删除字符串的所有实例,即使换句话说,就像这样: '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)
Run Code Online (Sandbox Code Playgroud)

piR*_*red 13

使用str.split和仅str.get使用locwhere 指定df.make == ''

df.loc[df.make == '', 'make'] = df.id.str.split().str.get(0)

print df

               id    make
0      abarth 1.4  abarth
1        abarth 1  abarth
2  land rover 1.3   rover
3    land rover 2   rover
4    land rover 5   rover
5      mazda 4.55   mazda
Run Code Online (Sandbox Code Playgroud)


小智 5

这很简单。使用方法如下:

df['make'] = df['id'].str.split(' ').str[0]
Run Code Online (Sandbox Code Playgroud)