2017-03-12 2 views
2

私は、次のデータフレームを持っている:別の場所で値を入力するためにdataFrameセルから値をフェッチする方法はありますか?

ID | Parent ID | Direction 
1 | 0  | North 
2 | 1  | South 
3 | 1  | West 
4 | 0  | East 

私が対応する親の方向に非ゼロの親ID」を持つすべての行の方向を変更する関数を書きたいです。

望ましい結果:

ID | Parent ID | Direction 
1 | 0  | North  #Ignore because Parent Id = 0 
2 | 1  | North  #Changed to Direction of Parent Id = 1 
3 | 1  | North  #Changed to Direction of Parent Id = 1 
4 | 0  | East  #Ignore because Parent Id = 0 

ここで上記のサンプルデータフレームを作成するためのコードです:

df = pd.DataFrame ({'ID' : [1,2,3,4], 
      'Parent ID' : [0,1,1,0], 
      'Direction' : ['North', 'South','West','East']}) 

私は関数を記述し、親IDにマップを呼び出してみましたが、私は失敗しました。

答えて

1

あなたはこれを試すことができます。

to_replace = df['Parent ID'] != 0 
df.loc[to_replace, 'Direction'] = df['Parent ID'][to_replace].map(df.set_index("ID").Direction)  
df 

enter image description here

関連する問題