程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了计算熊猫数据框中特定单词的出现次数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决计算熊猫数据框中特定单词的出现次数?

开发过程中遇到计算熊猫数据框中特定单词的出现次数的问题如何解决?下面主要结合日常开发的经验,给出你关于计算熊猫数据框中特定单词的出现次数的解决方法建议,希望对你解决计算熊猫数据框中特定单词的出现次数有所启发或帮助;

我想计算数据帧的每一行提到单词列表的次数 使用此代码

df["Count"] = (
    df['Token'].str.split()
    .apply(Counter)
    .apply(lambda counts: sum(word in counts for word in words))
)

我使用的是单词列表。

words = ['wooly','girl']

但是代码导致每个条目的值都为 0,这是不正确的。

我使用的数据是一个标记化的列表,如下所示:['uno','dos','one','two','tres','quatro','yes','wooly','bully','watch','come','git','matty','told','hattIE','thing','saw','big','horns','jaw','drive','lets','dont','take','chance','lseven','learn','dance','yeah','thats','get','someone','really','pull','wool','got','got']

这个列表我通过 df['Token'] = df['Token'].apply(str) 变成了一个字符串

解决方法

易于使用 defaultDict 中的 Countercollections

words = ['uno','dos','one','two','tres','quatro','yes','wooly','bully','watch','come','git','matty','told','hattie','thing','saw','big','horns','jaw','drive','lets','dont','take','chance','lseven','learn','dance','yeah','thats','get','someone','really','pull','wool','got','got']


from collections import defaultDict
Dict_count = defaultDict(int)
for item in words:
    Dict_count[item] += 1

或者:

from collections import Counter
counts = Counter(words)
,

要计算字符串中子字符串出现的次数,您可以这样做

String.count(subString)

因此,您可以将此函数应用于包含字符串的列:

String_occurrences = df.Token.apply(lambda x: sum([x.count(subString) for subsTing in ['wooly','girl']])

然后你只需要对计数求和

@R_19_10586@l_occurrences = String_occurrences.sum()
,

Counter 的返回是字典。

df["Count"] = (
    df['Token'].str.split()
    .apply(Counter)
    .apply(lambda counts: sum([counts[word] for word in words]))
)

如果 Token 列中的值已经是列表,则无需使用 str.split()

df["Count"] = (
    df['Token']
    .apply(Counter)
    .apply(lambda counts: sum([counts[word] for word in words]))
)
,

要计算 pandas 数据框中特定单词的出现次数,您可以使用以下代码。

from collections import Counter
    
def most_common_words(labels,quantity):

    words = [i.split(" ",1)[0] for i in labels]
    counter = Counter(words).most_common(quantity)
    df = pd.DataFrame(counter,columns=["Word","occurrence number"])\
                        .sort_values(by="occurrence number",ascending=TruE)
    return df

    
# Identify the most common words
df_most_common_words = most_common_words(words,20)
print(df_most_common_words)

大佬总结

以上是大佬教程为你收集整理的计算熊猫数据框中特定单词的出现次数全部内容,希望文章能够帮你解决计算熊猫数据框中特定单词的出现次数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。