基于tex的数据帧文本过滤

2024-06-07 14:01:32 发布

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

我需要一些帮助来运行一些数据过滤器。我有一个由文本组成的数据集。我还有一个单词列表。我想过滤数据的每一行,这样行中的剩余文本将只由list对象中的单词组成

words

(cell, CDKs, lung, mutations monomeric, Casitas, Background, acquired, evidence, kinases, small, evidence, Oncogenic )


data

ID  Text

0   Cyclin-dependent kinases CDKs regulate a 

1   Abstract Background Non-small cell lung  

2   Abstract Background Non-small cell lung 

3   Recent evidence has demonstrated that acquired

4   Oncogenic mutations in the monomeric Casitas  

所以在我的过滤器之后,我希望数据帧看起来像这样

data

ID  Text

0    kinases CDKs  

1   Background cell lung  

2   Background small cell lung 

3   evidence acquired

4   Oncogenic mutations monomeric Casitas  

我试着使用iloc和类似的函数,但我似乎没有得到它。有什么帮助吗


Tags: 数据文本过滤器cellsmallbackgroundmutationsevidence
2条回答

我不确定这是最优雅的解决方案,但你可以:

to_remove = ['foo', 'bar']
df = pd.DataFrame({'Text': [
    'spam foo& eggs', 
    'foo bar eggs bacon and lettuce', 
    'spam and foo eggs'
]})

df['Text'].str.replace('|'.join(to_remove), '')

您可以简单地使用^{}和一个简单的列表:

>>> df['Text'].apply(lambda x: ' '.join([i for i in x.split() if i in words]))
0                             kinases CDKs
1                     Background cell lung
2                     Background cell lung
3                        evidence acquired
4    Oncogenic mutations monomeric Casitas

另外,为了提高性能(O(1)平均查找时间),我建议您也这样做

相关问题 更多 >

    热门问题