【问题标题】:Count no. of matching words from one dataframe list to another dataframe list数数从一个数据框列表到另一个数据框列表的匹配词
【发布时间】:2021-12-02 15:17:09
【问题描述】:

我有 2 个数据框,我想在其中计算编号。从 df1 到 df 2 的匹配词数

df1 是属于每个部门的关键字列表,例如教育、金融、交通等

df1:

Sector Content
Education ['school', 'children', 'learning', 'enrichment' ]
Finance ['banks', 'insurance', 'moneylender']

df 2 是从网站抓取的数据。单词已经被拆分和清理,并且是列表形式。

df2:

Company Name Website Info
ABC ['school', 'enrichment']
DEF ['banks', 'children', 'school' ]

我想找出答案。 df1 中每个扇区匹配的单词数。
预期结果:

Company Name Website Info No. of Matched Words Education No. of Matched words Finance
ABC ['school', 'enrichment'] 2 0
DEF ['banks', 'children', 'school' ] 2 1

【问题讨论】:

    标签: python list dataframe


    【解决方案1】:

    有两种解决方案:

    1. 遍历时间复杂度为 O(n^2) 的列表

      
      education= ['school', 'children', 'learning', 'enrichment' ]
      abc = ['school', 'enrichment']
      count = 0
      for element in abc:
          if element in education:
              count+=1
      
    2. 使用时间复杂度为 O(n) 的 collections.Counter()

      
      counters = collections.Counter(education+abc)
      count = len([x for x in list(dict(counters).values()) if x >1])
      

    显然第二种方案更好

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多