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

2024-10-02 06:25:15 发布

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

我在下面创建了一个带有ID和text列的虚拟数据集,其中包含一些公司名称的字符串列。你知道吗

  # 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行中,但在最后一个字符串中出现了两次,因此is count total是4。你知道吗


Tags: 字符串textidappleamazondfcountgoogle
2条回答

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

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

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

   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']
   y=[' '.join(set(yy.split(' '))) for yy in y] 
   df=pd.DataFrame({'ID':x,'text':y})

相关问题 更多 >

    热门问题