【问题标题】:pythonic way to count the number of times words from a list / set occur in a dataframe columnpythonic方法来计算列表/集合中的单词出现在数据框列中的次数
【发布时间】:2020-06-28 21:15:35
【问题描述】:

给定一个列表/一组标签

labels = {'rectangle', 'square', 'triangle', 'cube'}

和一个数据框df,

df = pd.DataFrame(['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], columns=['text'])

我想知道我的一组标签中的每个单词在数据框的文本列中出现了多少次,并创建一个新列,其中包含前 X 个(可能是 2 或 3 个)重复次数最多的单词。如果两个单词的重复次数相同,那么它们可以出现在列表或字符串中

输出:

pd.DataFrame({'text' : ['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], 'best_labels' : [{'rectangle' : 2, 'square' : 1, 'cube' : 1}, {'triangle' : 1, 'circle' : 1}, np.nan]})                                                                                                                          
                                                                                                                      
df['best_labels'] = some_function(df.text) 

【问题讨论】:

  • pd.DataFrame({'text' : ['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], 'best_labels' : [{'rectangle' : 2, 'square' : 1, 'cube' : 1}, {'triangle' : 1, 'circle' : 1}, np.nan]}) 是您拥有的东西,还是预期输出的一部分?
  • 为什么不在best_labels 中留下一个空集以应对没有匹配的情况? np.nan(“不是数字”)是一个奇怪的“默认”值,因为没有一个有效值是数字

标签: python pandas dataframe count find-occurrences


【解决方案1】:
from collections import Counter

labels = {'rectangle', 'square', 'triangle', 'cube'}    
df = pd.DataFrame(['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], columns=['text'])
    
df['best_labels'] = df.text.apply(lambda x: {k: v for k, v in Counter(x.split()).items() if k in labels} or np.nan)    
print(df)

打印:

                                    text                               best_labels
0  rectangle rectangle in my square cube  {'rectangle': 2, 'square': 1, 'cube': 1}
1               triangle circle not here                           {'triangle': 1}
2                           nothing here                                       NaN

【讨论】:

    【解决方案2】:

    另一种可视化数据的方法是使用矩阵:

    (df['text'].str.extractall(r'\b({})\b'.format('|'.join(labels)))
               .groupby(level=0)[0]
               .value_counts()
               .unstack()
               .reindex(df.index)
               .rename_axis(None, axis=1))
    
       cube  rectangle  square  triangle
    0   1.0        2.0     1.0       NaN
    1   NaN        NaN     NaN       1.0
    2   NaN        NaN     NaN       NaN
    

    这个想法是从labels中指定的行中提取文本,然后找出每个句子出现了多少次。

    这看起来像什么?是的,你猜对了,一个稀疏矩阵。

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多