python - 将子字符串循环到新列
问题描述
我正在研究一个看起来有点像这样的数据集(使用python和pandas):
date text
0 Jul 31 2020 Sentence Numero Uno #cool
1 Jul 31 2020 Second sentence
2 Jul 31 2020 Test sentence 3 #thanks
所以我使用我在网上找到的这段代码来删除 Hashtags 之类#cool
#thanks
的,并将所有内容都设为小写。
for i in range(df.shape[0]) :
df['text'][i] = ' '.join(re.sub("(#[A-Za-z0-9]+)", " ", df['text'][i]).split()).lower()
那行得通,但是我现在不想完全删除主题标签,而是将它们保存在额外的列中,如下所示:
date text hashtags
0 Jul 31 2020 sentence numero uno #cool
1 Jul 31 2020 second sentence
2 Jul 31 2020 test sentence 3 #thanks
任何人都可以帮助我吗?我怎样才能做到这一点?提前致谢。
编辑:由于某些字符串包含多个主题标签,因此应将其作为列表存储在主题标签列中。
解决方案
Series.str.findall
与 一起使用Series.str.join
:
df['hashtags'] = df['text'].str.lower().str.findall(r"(\#[A-z0-9]+)").str.join(' ')
推荐阅读
- python - 将 API 值的响应更改为其他值
- r - 在 ggplot2 中“反向”使用 fct_infreq()
- c++ - 使用 string_view 搜索 unordered_map
- python - 在 Tkinter 中更改函数中的变量
- python - 散景中的简单 1 层面积图
- java - Java Spring LDAP Auth:总是失败,但在 Nodejs 中测试类似配置时效果很好
- concurrency - 函数式语言如何处理共享状态数据?
- exception - 如何使用动态变量和中止控制在方案中定义异常?
- python - Python - 检查列是否包含列表中的值,返回值
- php - PHP SQL注入在UPDATE语句中绑定动态变量