2017-06-07 1 views
0

は私のサンプルデータは、次のようになります。今度は、以下のコードを使用してインプレッションを集計する方法を理解しました。私はこれらのクエリに関連した平均的な印象を表示するために別の列を必要とする。ここN-グラムの分析は、Pythonでここ

enter image description here

:よう

def n_grams(txt): 
grams = list() 
words = txt.split(' ') 
for i in range(len(words)): 
    for k in range(1, len(words) - i + 1): 
     grams.append(" ".join(words[i:i+k])) 
return pd.Series(grams) 


counts = df['query'].apply(n_grams).join(df) 
result = counts.drop("query", axis=1).set_index("impression").unstack() .rename("ngram").dropna().reset_index() .drop("level_0", 
axis=1).groupby("ngram")["impression"].sum() 
result = result.to_frame() 
result['query'] = result.index 
result['ngram'] =result['query'].str.split().apply(len) 
result = result.groupby(['ngram','query'])['impression'].sum() 
result = result.reset_index() 
result = result.sort_values(['ngram', 'impression'], ascending=[True, False]) 

結果が返されます。たとえば、「栄養」という単語が4回表示されるため、平均インプレッション数は100/4 = 25になります。また、このクエリが別の列に何回表示されるかを示したいとします。最終的な結果は次のようになります。enter image description here

答えて

0

このコードは、bigramsからの「栄養」などのユニグラムの数を取得するのに役立ちます。

2gram=result[result['ngram']==2] 
2gram=2gram.reset_index() 
#create an empty dictionary to store count of words in bigrams 
words=dict() 
for i in range(0,len(2gram): 
    query_wrds=2gram.loc[i,'query'].split() 
     for item in query_words: 
      if item not in words: 
       words[item]=1 
      else: 
       words[item]+=1 
#to get count of word 'nutrition' 
nut_ct=words['nutrition'] 
関連する問題