我有類似于以下示例的網站訪問者資料:
| ID | 頁 |
|---|---|
| 001 | /冰淇淋,/百吉餅,/百吉餅/風味 |
| 002 | /pizza, /pizza/flavors, /pizza/recipe |
我想轉換到下面,在那里我可以計算他們訪問我網站中處理特定內容的部分的次數。用逗號分隔的所有瀏覽量的一般計數也會很好。
| ID | bagel_count |
|---|---|
| 001 | 2 |
| 002 | 0 |
| ID | 披薩計數 |
|---|---|
| 001 | 0 |
| 002 | 3 |
| ID | total_pages_count |
|---|---|
| 001 | 3 |
| 002 | 3 |
我可以選擇在 SQL 或 Python 中執行,但我不確定哪個更容易,因此我為什么要問這個問題。
我參考了以下問題,但它們沒有達到我的目的:
計算字串中字符出現的次數(這很接近,但我不確定如何應用于資料幀)
計算一個詞的出現次數
計算表列中的單詞出現次數
使用 SQL 查詢計算單詞出現次數
uj5u.com熱心網友回復:
我們可以做split然后explode得到你的結果crosstab
df['pages'] = df.pages.str.split(r'[/, ]')
s = df.explode('pages')
out = pd.crosstab(s['id'], s['pages']).drop('', axis=1)
out
Out[427]:
pages bagels flavors ice-cream pizza recipe
id
1 2 1 1 0 0
2 0 1 0 3 1
uj5u.com熱心網友回復:
如果您更喜歡 SQL,我會走這條路。我通常將重點放在報告應用程式上,但如果你真的堅持,Snowflake 有很好的檔案供你從這里獲取
with cte (id, pages) as
(select '001', '/ice-cream, /bagels, /bagels/flavors' union all
select '002', '/pizza, /pizza/flavors, /pizza/recipe')
select id,
t2.value,
count(*) as word_count,
length(pages)-length(replace(pages,',','')) 1 as user_page_count
from cte, lateral split_to_table(translate(cte.pages, '- ,','/'),'/') as t2--normalize word delimiters using translate(similar to replace)
where t2.value in ('bagels','pizza') --your list goes here
group by id, pages, t2.value;
uj5u.com熱心網友回復:
我個人喜歡將正則運算式與組一起使用,然后分解成一個 df,然后我將其合并回 main。與該split方法相比,這有幾個優點,主要是節省了過多的記憶體使用量,從而顯著提高了性能。
import re
from typing import List, Dict
import pandas as pd
my_words = [
'bagels',
'flavors',
'ice-cream',
'pizza',
'recipe'
]
def count_words(string:str, words:List[str]=my_words) -> Dict[str, int]:
"""
Returns a dictionary of summated values
for selected words contained in string
"""
# Create a dictionary to return values
match_dict = {x:0 for x in words}
# Numbered capture groups with word boundaries
# Note this will not allow pluralities, unless specified
# Also: cache (or frontload) this value to improve performance
my_regex_string = '|'.join((fr'\b({x})\b' for x in words))
my_pattern = re.compile(my_regex_string)
for match in my_pattern.finditer(string):
value = match.group()
match_dict[value] =1
return match_dict
# Create a new df with values from function
new_df = df['pages'].apply(match_words).apply(pd.Series)
bagels flavors ice-cream pizza recipe
0 2 1 1 0 0
1 0 1 0 3 1
# Merge back to the main df
df[['id']].merge(new_df, left_index=True, right_index=True)
id bagels flavors ice-cream pizza recipe
0 1 2 1 1 0 0
1 2 0 1 0 3 1
uj5u.com熱心網友回復:
由于其優雅而將@BENY 的答案標記為正確,但我找到了一種在 python 中執行此操作的方法,專注于特定關鍵字 - 假設df看起來像我的原始表格
df['bagel_count'] = df["pages"].str.count('bagel')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/369402.html
