2017-02-23 5 views
1

私はこのようになりますDF持っている:私は、グループごとに行いたいのですがどのような検索類似したグループ別の列の値の交点に基づいて

Group Attribute 

Cheese Dairy 
Cheese Food 
Cheese Curd 
Cow  Dairy 
Cow  Food 
Cow  Animal 
Cow  Hair 
Cow  Stomachs 
Yogurt Dairy 
Yogurt Food 
Yogurt Curd 
Yogurt Fruity 

が、それは次のように、ほとんどのグループを見つけることですが属性の共通部分に基づいています。私がしたい最後のフォームは次のとおりです:

Group TotalCount LikeGroup CommonWords PCT 

Cheese 3   Yogurt  3   100.0 
Cow  5   Cheese  2   40.0 
Yogurt 4   Cheese  4   75.0 

これは1つの質問でたくさん質問するかもしれないことがわかります。私はそれを多用することができますが、ただ一つのグループと他のグループとの間でさえも、属性の交差の数を得ることは本当に失われています。私が正しい方向に私を送るチーズとヨーグルトの交差数を見つけることができれば。

データフレーム内で実行できますか?私はいくつかのリストを作成し、すべてのペアのリストの間で交差を行い、新しいリストの長さを使ってパーセンテージを得ることができます。ヨーグルトのために例えば

、:

>>>Yogurt = ['Dairy','Food','Curd','Fruity'] 
>>>Cheese = ['Dairy','Food','Curd'] 

>>>Yogurt_Cheese = len(list(set(Yogurt) & set(Cheese)))/len(Yogurt) 
0.75 

>>>Yogurt = ['Dairy','Food','Curd','Fruity'] 
>>>Cow = ['Dairy','Food','Animal','Hair','Stomachs'] 

>>>Yogurt_Cow = len(list(set(Yogurt) & set(Cow)))/len(Yogurt) 
0.5 

>>>max(Yogurt_Cheese,Yogurt_Cow) 
0.75 

答えて

3

私はあなたのサンプルの私自身の小型版を作成しましたアレイ。私のサンプルデータのための

import pandas as pd 
from itertools import permutations 

df = pd.DataFrame(data = [['cheese','dairy'],['cheese','food'],['cheese','curd'],['cow','dairy'],['cow','food'],['yogurt','dairy'],['yogurt','food'],['yogurt','curd'],['yogurt','fruity']], columns = ['Group','Attribute']) 
count_dct = df.groupby('Group').count().to_dict() # to get the TotalCount, used later 
count_dct = count_dct.values()[0] # gets rid of the attribute key and returns the dictionary embedded in the list. 

unique_grp = df['Group'].unique() # get the unique groups 
unique_atr = df['Attribute'].unique() # get the unique attributes 

combos = list(permutations(unique_grp, 2)) # get all combinations of the groups 
comp_df = pd.DataFrame(data = (combos), columns = ['Group','LikeGroup']) # create the array to put comparison data into 
comp_df['CommonWords'] = 0 

for atr in unique_atr: 
    temp_df = df[df['Attribute'] == atr] # break dataframe into pieces that only contain the attribute being looked at during that iteration 

    myl = list(permutations(temp_df['Group'],2)) # returns the pairs that have the attribute in common as a tuple 
    for comb in myl: 
     comp_df.loc[(comp_df['Group'] == comb[0]) & (comp_df['LikeGroup'] == comb[1]), 'CommonWords'] += 1 # increments the CommonWords column where the Group column is equal to the first entry in the previously mentioned tuple, and the LikeGroup column is equal to the second entry. 

for key, val in count_dct.iteritems(): # put the previously computed TotalCount into the comparison dataframe 
    comp_df.loc[comp_df['Group'] == key, 'TotalCount'] = val 

comp_df['PCT'] = (comp_df['CommonWords'] * 100.0/comp_df['TotalCount']).round() 

私は正しいと思わ出力

Group LikeGroup CommonWords TotalCount PCT 
0 cheese  cow   2   3 67 
1 cheese yogurt   3   3 100 
2  cow cheese   2   2 100 
3  cow yogurt   2   2 100 
4 yogurt cheese   3   4 75 
5 yogurt  cow   2   4 50 

を得ました。

+0

これはすべてのグループの一般的な単語の割合を示していますが、私はここから簡単に行くことができます。これは私が求めていたものよりも有用かもしれないと思います。どうもありがとう。 –

+0

問題ありません。誰かが似たような質問をした場合には、その答えを受け入れるべきです;) – Nemo

1

あなたがこれを解読するために集約戦略を作ることができるはずのように思えます。これらのコーディングサンプルを見て、あなたの例に示すようにピースメールに取り組むのではなく、データフレーム上でキーと集約関数を構築する方法を考えてみてください。

は、あなたのPython環境でこれを実行してみてください(これはPython 2.7を使用してJupyterノートPCで作成された)、それはあなたのコードについていくつかのアイデアを与えるかどうかを確認:

np.random.seed(10) # optional .. makes sure you get same random 
         # numbers used in the original experiment 
df = pd.DataFrame({'key1':['a','a','b','b','a'], 
        'key2':['one','two','one','two','one'], 
        'data1': np.random.randn(5), 
        'data2': np.random.randn(5)}) 

df 
group = df.groupby('key1') 
group2 = df.groupby(['key1', 'key2']) 
group2.agg(['count', 'sum', 'min', 'max', 'mean', 'std']) 
関連する問題