Pandas列中实例的自引用

2024-09-27 07:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下测向

 SampleID ParentID
0  S10        S20    
1  S10        S30    
2  S20        S40     
3  S30              
4  S40       

如何将另一行的id放入“ParentID”列而不是字符串中?在

预期结果:

^{pr2}$

对于这个问题,我发现的最接近的结果是: How to self-reference column in pandas Data Frame?


Tags: to字符串inselfidcolumnhowreference
2条回答

我想您可以使用^{},然后分配列index

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      

另一个使用^{}dict的解决方案,其中使用值交换密钥:

^{pr2}$

通过传递要替换的值的映射列表来使用replace

df.ParentID.replace(df.SampleID.tolist(), df.index.tolist(), inplace=True)

df
Out[22]: 
  SampleID  ParentID
0      S10       2.0
1      S10       3.0
2      S20       4.0
3      S30       NaN
4      S40       NaN

相关问题 更多 >

    热门问题