【问题标题】:Python Pandas: count the number of words in a data frame [duplicate]Python Pandas:计算数据框中的单词数[重复]
【发布时间】:2016-11-12 20:53:03
【问题描述】:

有一个大数据框名为dataframe1。例如(只是几个):

 date                  text                             name
 1      I like you hair, do you like it              screen1
 2      beautiful sun and wind                       screen2
 3      today is happy, I want to got school         screen3
 4      good movie                                   screen4
 5      thanks god                                   screen1
 6      you are my son and I love you                screen2
 7      the company  is good                         screen1
 8      no one can help me, only you                 screen2
 9      the book is good and I read it everyday      screen3
 10      water is the source of love                 screen4
 11     I like you hair, do you like it              screen1
 12     my love man is leaving                       screen2

我想使用函数count_noun(str)来计算每个名字的文字(比如dataframe1中所有screen1的文字)的字数。此外, con_noun(str) 没问题并且完成了。

我想提取数据框中所有具有相同名称的文本并计算名词计数。请不要关注函数count_noun(str),我已经写完了。

我的代码:

import pandas as pd
import numpy as np

screen_name_unique = list(set(dataframe1['name']))
for name in screen_name_unique:
   dataframe_text = dataframe1[dataframe1.name == name]
   count = noun_count(dataframe['text'])



 def noun_count (str):
    words_len = len(str)
    return words_len

我发现不对,不知道怎么解决,比如把name1的所有文本提取成字符串发送给函数:noun_count(str),请给我你的手,谢谢!

【问题讨论】:

  • 如果您想了解更多信息,请告诉我
  • 怎么了?你怎么知道 noun_count 没有错?尝试打印计数,因为现在您不返回任何内容。
  • 感谢cmets,请不要关注noun_count()函数。我只想提取每个名称的所有文本,并计算名词单词的数量。在提取每个名称的文本后,我不知道如何解决它。下一步我不知道。
  • @Merlin,函数 noun_count(Str) ,参数str为字符串类型
  • 除非您包含该功能,否则很难弄清楚什么不起作用。

标签: pandas dataframe python-3.5


【解决方案1】:

我已经解决了,使用apply()函数来计数

import pandas as pd
import numpy as np

screen_name_unique = list(set(dataframe1['name']))
for name in screen_name_unique:
  dataframe_text = dataframe1[dataframe1.name == name]
  dataframe_text['text'].apply(noun_count)



def noun_count (str):
  words_len = len(str)
  return words_len

【讨论】:

  • len(str) 将计算字符数,而不是字数。
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多