Python 从一列字符串中计算单词的唯一时间

Python 从一列字符串中计算单词的唯一时间,python,string,Python,String,我在下面创建了一个虚拟数据集,其中包含ID和文本列,其中包含包含一些公司名称的字符串列 # create dummy data frame with text columns x=[1,2,3,4,5] y=['apple google microsoft spotify alibaba','google microsoft','spotify google microsoft amazon','amazon google apple','amazon google spot

我在下面创建了一个虚拟数据集,其中包含ID和文本列,其中包含包含一些公司名称的字符串列

  # create dummy data frame with text columns
    x=[1,2,3,4,5]
    y=['apple google microsoft spotify alibaba','google microsoft','spotify google microsoft amazon','amazon google apple','amazon google spotify amazon']
    df=pd.DataFrame({'ID':x,'text':y})
    df
我还有一份名单,上面还有公司的名字

# create list of companies
listtry=['apple','google','microsoft','spotify','alibaba','amazon','structo']
我想做的是计算每个公司在主dataframe文本列中出现的行数,而不是跨文本列字符串出现的实际计数

下面的代码给出了实际发生次数计数

    # search amd count 
df2 = list()
for company in listtry :
    df2.append(df.text.str.count(company).sum())
df3=pd.DataFrame({'company':listtry,'count':df2})
df4=df3.sort_values('count',ascending=False)
df4

# gives results

     company  count
1     google      5
5     amazon      4
2  microsoft      3
3    spotify      3
0      apple      2
4    alibaba      1
6    structo      0

预期输出是Amazon的3倍,因为它只出现在3行中,但在最后一个字符串中出现了两次,因此计数总数为4。

为什么不使用
set
删除重复项?(见第三行)


再次尝试,将
count
更改为
contains
,并获取df的长度:

for company in listtry :
    df2.append(len(df[df.text.str.contains(company)]))  # only changes here

是的,这是一种可能的方法,但我在实际数据中变量Y中的字符串是巨大的文章。对它们进行预处理以获得唯一的单词将使其更加耗时。
for company in listtry :
    df2.append(len(df[df.text.str.contains(company)]))  # only changes here