簡體   English   中英

計算可以包含在 DataFrame 列中的集合詞的出現次數,該列由全局和單行尺度上的字符串列表組成

[英]Count occurences of set words that can be contained in a DataFrame column composed by a list of strings on a global and single row scale

我希望我沒有創建重復的大聲笑,但我花了幾個小時尋找與我的問題類似的東西:)

說,我有以下輸入:

foo= {"Brand":["loc doc poc",
               "roc top mop",
               "loc lot not",
               "roc lot tot",
               "loc bot sot",
               "nap rat sat"] }

word_list=["loc","top","lot"]
df=pd.DataFrame(foo) 

2 所需輸出

1存儲事件的字典

2包含每行出現次數的新列

#Outputs: 
counter_dic={"loc":3,"top":1,"lot":2}

            Brand   count
0   loc  doc  poc       1
1   roc  top  mop       1
2   loc  lot  not       2
3   roc  lot  tot       1
4   toc  bot  sot       1
5   nap  rat  sat       0

我唯一的想法:

  • 計算一組術語出現的次數。 我可以創建一個詞袋,然后根據字典鍵進行過濾嗎?

如果您發現類似的問題,這顯然可以關閉。

我檢查了以下

這是最相似的之一

檢查字符串是否在 Pandas DataFrame 中

Python 列出查找字符串出現的次數

統計字符串列表中 Substring 的出現次數

這是一種使用str.count創建臨時計數 DataFrame 的潛在解決方案,這將有助於兩個輸出。

df_counts = pd.concat([df['Brand'].str.count(x).rename(x) for x in word_list], axis=1)

好像:

   loc  top  lot
0    1    0    0
1    0    1    0
2    1    0    1
3    0    0    1
4    1    0    0
5    0    0    0

1 - 存儲事件的字典

df_counts.sum().to_dict()

[出去]

{'loc': 3, 'top': 1, 'lot': 2}

2 - 包含每行出現次數的新列

df['count'] = df_counts.sum(axis=1)

[出去]

         Brand  count
0  loc doc poc      1
1  roc top mop      1
2  loc lot not      2
3  roc lot tot      1
4  loc bot sot      1
5  nap rat sat      0

這是一種將計數轉換為字典形式的方法:

df['Brand'].str.split(' ').explode().to_frame('Brand').groupby('Brand').size().loc[word_list].to_dict()

這是一種獲取計數的方法:

df['count'] = df['Brand'].str.get_dummies(sep=' ').loc[:,word_list].sum(axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM