python - 获取两个数据帧之间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
'''
解决方案
这是简单的解决方案
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')
推荐阅读
- kubernetes - 如何诊断未生成证书管理器的证书机密?
- amazon-web-services - DynamoDB 中的热分区问题随着新的按需功能而消失了吗?
- reactjs - 如何在带有 webpack 的 React 应用程序中的 web 工作者中使用 ES6 模块?
- javascript - 如何在 React 中自定义 Material UI?
- python - 在循环中跳过多次迭代
- eclipse - Eclipse 等效于 Intellij 动态属性
- python - RuntimeError:CUDA 错误:内存不足 - DCGAN with image_size = 256
- c# - DotNetCore WebAPI:使用 Postman 的命名空间解析 xml 的问题
- java - 从 imageView 更新 Java Fx 图像
- apache-spark - Spark Driver 内存计算