![](/img/trans.png)
[英]Python sort strings by count of appearances of the strings in the list
[英]Count and map number of appearances of strings
我正在使用Python中的applymap將特定的關鍵字與文本數據映射。 假設我要檢查關鍵字“ hello”與所有行上的文本數據匹配的頻率。 Applymap為我提供了所需的矩陣結果,但是只有“ True”或“ False”,而不是出現次數。
我試圖將count()與我的applymap函數連接起來,但無法使其正常工作。
最小的工作示例如下:
import pandas as pd
import numpy as np
df = pd.DataFrame({'text': ['hello hello', 'yes no hello', 'good morning']})
keys = ['hello']
keyword = pd.DataFrame({0:keys})
res = []
for a in df['text']:
res.append(keyword.applymap(lambda x: x in a))
map = pd.concat(res, axis=1).T
map.index = np.arange(len(map))
#Output
map
0
0 True
1 True
2 False
#Desired Output with 'hello' appearing twice in the first row, once in the second and zero in the third of df.
0
0 2
1 1
2 0
我正在尋找一種方法來保留我的applymap函數以獲取矩陣形式,但將True(1)和False(0)替換為外觀數量,例如上面顯示的所需輸出。
代替測試列表中的項目:
res.append(keyword.applymap(lambda x: x in a))
#x == a
您應該使用:
res.append(keyword.applymap(lambda x: str.count(a, x)))
#計數“ a”的出現
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.