2016-07-02 6 views
1

私は相対的な人のためにデータフレームにいくつかのリサーチャーを行っています。しかし、私が兄弟を見つけたら管理できないので、特定の列にすべてを書き留める方法を見つけることができません。ここでは一例に従ってください:私が欲しいものPython Pandas:groupbyのメンバーを返すにはどうすればいいですか

cols = ['Name','Father','Brother'] 
df = pd.DataFrame({'Brother':'', 
        'Father':['Erick Moon','Ralph Docker','Erick Moon','Stewart Adborn'], 
        'Name':['John Smith','Rodolph Ruppert','Mathew Common',"Patrick French"]     
        },columns=cols) 

df 
      Name   Father   Brother 
0  John Smith Erick Moon   
1 Rodolph Ruppert Ralph Docker   
2 Mathew Common Erick Moon   
3 Patrick French Stewart Adborn 

はこれです:

  Name   Father   Brother 
0  John Smith Erick Moon  Mathew Common  
1 Rodolph Ruppert Ralph Docker   
2 Mathew Common Erick Moon  John Smith 
3 Patrick French Stewart Adborn 

私は任意のヘルプをapreciate!

+1

このデータセットは、男性のみが含まれていますか? 2人以上の兄弟がいますか? – ayhan

+0

これは役に立つかもしれません:http://pandas.pydata.org/pandas-docs/stable/reshaping.html –

+0

いいえ、私はちょうど擬似コードを作った。女性もいます。また、2人以上の兄弟がいる可能性もあります。私は形を変えることに目を向ける。私はgroupbyを試みたが、それは2回書き直すので、他の兄弟だけを得ることができなかった... – nicmano

答えて

1

ここでは、すべての兄弟をリストとして含むBrother列を作成し、それ自体を別々に削除してみることをお勧めします。コードはおそらく最適化することができますがどこから起動することができます。私は、これは動作するはずだと思う

import numpy as np 
import pandas as pd 
df['Brother'] = df.groupby('Father')['Name'].transform(lambda g: [g.values]) 
def deleteSelf(row): 
    row.Brother = np.delete(row.Brother, np.where(row.Brother == row.Name)) 
    return(row) 
df.apply(deleteSelf, axis = 1) 

#    Name   Father   Brother 
# 0  John Smith  Erick Moon [Mathew Common] 
# 1 Rodolph Ruppert Ralph Docker    [] 
# 2 Mathew Common  Erick Moon  [John Smith] 
# 3 Patrick French Stewart Adborn    [] 
+0

それは素晴らしい作品!私は非常に適切な解決策を考えています! – nicmano

0
def same_father(me, data): 
    hasdad = data.Father == data.at[me, 'Father'] 
    notme = data.index != me 
    isbro = hasdad & notme 
    return data.loc[isbro].index.tolist() 

df2 = df.set_index('Name') 
getbro = lambda x: same_father(x.name, df2) 
df2['Brother'] = df2.apply(getbro, axis=1) 

(未テスト)

関連する問題