首页 > 解决方案 > 获取两个数据帧之间python中包含子字符串的字符串行数的最快方法

问题描述

我有两个数据框,一个有单词,另一个有文本。我想获取第一个数据框中包含该单词的所有行的计数。

字=

ID   | Word
------------
1    | Introduction
2    | database
3    | country 
4    | search

文字 =

ID   | Text
------------
1    | Introduction to python
2    | sql is a database
3    | Introduction to python in our country
4    | search for a python teacher in our country

我想要的最终输出是

ID   | Word  |  Count
---------------------
1    | Introduction  | 2
2    | database  | 1
3    | country  |  1
4    | search  |  2

我在单词 df 中有 200000 行,在文本中有 55000 行(每个文本的长度约为 2000 个单词)df。使用以下代码完成整个过程大约需要 76 小时

'''

def docCount(docdf, worddf):
    final_dict = {}
    for i in tqdm(worddf.itertuples()):
        docdf["Count"] = docdf.Text.str.contains(i[2])
        temp_dict = {i[2]: docdf.Count.sum()}
        final_dict = dict(Counter(final_dict)+Counter(temp_dict))
    return final_dict

'''

标签: pythonpython-3.xpandasnltk

解决方案


这是简单的解决方案

world_count = pd.DataFrame(
    {'words': Word['Word'].tolist(),
     'count': [Text['Text'].str.contains(w).sum() for w in words],
    }).rename_axis('ID')

输出:

world_count.head()

'''
           words  count
ID                     
0   Introduction      2
1       database      1
2        country      2
3         search      1
'''

逐步解决方案:

# Convert column to list
words = Word['Word'].tolist()

# Get the count
count = [Text['Text'].str.contains(w).sum() for w in words]

world_count = pd.DataFrame(
    {'words': words,
     'count': count,
    }).rename_axis('ID')

小费:

我建议你转换为小写,这样你就不会因为大写/小写而错过任何计数

import re
import pandas as pd

world_count = pd.DataFrame(
    {'words': Word['Word'].str.lower().str.strip().tolist(),
     'count': [Text['Text'].str.contains(w,flags=re.IGNORECASE, regex=True).sum() for w in words],
    }).rename_axis('ID')

推荐阅读