首页 > 解决方案 > 将子字符串循环到新列

问题描述

我正在研究一个看起来有点像这样的数据集(使用pythonpandas):

           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

任何人都可以帮助我吗?我怎样才能做到这一点?提前致谢。

编辑:由于某些字符串包含多个主题标签,因此应将其作为列表存储在主题标签列中。

标签: pythonpandas

解决方案


Series.str.findall与 一起使用Series.str.join

df['hashtags'] = df['text'].str.lower().str.findall(r"(\#[A-z0-9]+)").str.join(' ')

推荐阅读