pandas数据帧返回列的字符串中的第一个字

2024-05-16 00:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框:

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']

我应该混合并匹配regex和df.apply中的变量吗?

df.id = df.apply(lambda x: x['id'].replace(r'\b' + x['series'], ''), axis =1)

Tags: 数据lambda字符串iddfreplaceseriesapply
3条回答

使用str.splitstr.get并仅在df.make == ''处使用loc分配

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

考虑一个带有loc的正则表达式解决方案,它在第一个空格之前提取所有内容:

df.loc[df['make']=='', 'make'] = df['id'].str.extract('(.*) ', expand=False)

或者,使用numpy的where,它允许if/then/else条件逻辑:

df['make'] = np.where(df['make']=='', 
                      df['id'].str.extract('(.*) ', expand=False), 
                      df['make'])

如果我正确地回答了您的问题,您可以使用replace函数:

df.make = df.make.replace("", test.id)

相关问题 更多 >