Pandas - Self reference of instances in column
<p>I have the following DF</p>

<pre><code> SampleID ParentID
0  S10        S20    
1  S10        S30    
2  S20        S40     
3  S30              
4  S40       
</code></pre>

<p>How can I put the id of the other row in the column 'ParentID' instead of the string?</p>

<p>Expected result:</p>

<pre><code> SampleID ParentID 
0  S10        2    
1  S10        3    
2  S20        4   
3  S30              
4  S40              
</code></pre>

<p>The closest result I found for this problem was:
<a href="http://stackoverflow.com/questions/28101317/how-to-self-reference-column-in-pandas-data-frame">How to self-reference column in pandas Data Frame?</a></p>

<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> and then assign column <code>index</code>:</p>

<pre><code>df1 = pd.merge(df[['SampleID']].reset_index(), 
               df[['ParentID']], 
               left_on='SampleID',
               right_on='ParentID')
print (df1)
   index SampleID ParentID
0      2      S20      S20
1      3      S30      S30
2      4      S40      S40

df['ParentID'] = df1['index']
df.fillna('', inplace=True)
print (df)
  SampleID ParentID
0      S10        2
1      S10        3
2      S20        4
3      S30         
4      S40      
</code></pre>

<hr>

<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> and <code>dict</code> where swap keys with values:</p>

<pre><code>d = dict((v,k) for k,v in df.SampleID.iteritems())
print (d)
{'S10': 1, 'S40': 4, 'S20': 2, 'S30': 3}

df.ParentID = df.ParentID.map(d)
df.ParentID.fillna('', inplace=True)
print (df)
  SampleID ParentID
0      S10        2
1      S10        3
2      S20        4
3      S30         
4      S40         
</code></pre>

python pandas