首页 > 解决方案 > 在多个条件下为一列中的每一行提取第一个单词

问题描述

我有一个数据集包含一列字符串。看起来像

df.a=[['samsung/windows','mobile unknown','chrome/android']]. 我正在尝试获取每行的第一个单词来替换当前字符串,例如[['samsung','mobile','chrome']]

我申请了:

df.a=df.a.str.split().str.get(0)

这给了我第一个词,但带有“/”

df.a=[words.split("/")[0] for words in df.a]

这只会拆分包含“/”的字符串

我可以使用一行得到预期的结果吗?

标签: pythonpandasstrsplitmultiple-conditions

解决方案


仅使用re.findall()和获取字母数字

import re
df['a'] = df['a'].apply(lambda x : re.findall(r"[\w']+",x)[0])

推荐阅读