这是我的数据
id keyword
1 transfer
2 atm transfer
3 atm
4 ulta transfer
如果只剩下一个单词,我想删除transfer
个单词,但是如果只剩下transfer
个单词,则该单词仍然保留,另一个单词是atm
,但只有{{ 1}}和atm
左边,我们选择transfer
我的预期输出
atm
希望这个问题很清楚
答案 0 :(得分:2)
df['keyword_2'] = df['keyword'].mask(df['keyword'] != 'transfer',
df['keyword'].str.replace('transfer', '').str.strip())
print (df)
id keyword keyword_2
0 1 transfer transfer
1 2 atm transfer atm
2 3 atm atm
3 4 ulta transfer ulta
另一种不带分隔线但带有join
和split
的解决方案:
print (df)
id keyword
0 1 transfer
1 2 atm transfer
2 3 atm
3 4 ulta transfer v
df['keyword_2'] = [' '.join(y for y in x.split() if y != 'transfer')
if x != 'transfer' else x for x in df['keyword']]
print (df)
id keyword keyword_2
0 1 transfer transfer
1 2 atm transfer atm
2 3 atm atm
3 4 ulta transfer v ulta v
答案 1 :(得分:1)
d['keyword'].apply(lambda x: x.replace('transfer','') if len(x.split(' ')) > 1 else x )
输出
0 transfer
1 atm
2 atm
3 ulta
Name: keyword, dtype: object