2024-09-27 07:27:43 发布
网友
我有以下测向
SampleID ParentID 0 S10 S20 1 S10 S30 2 S20 S40 3 S30 4 S40
如何将另一行的id放入“ParentID”列而不是字符串中?在
预期结果:
对于这个问题,我发现的最接近的结果是: How to self-reference column in pandas Data Frame?
我想您可以使用^{},然后分配列index:
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的解决方案,其中使用值交换密钥:
dict
通过传递要替换的值的映射列表来使用replace:
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
我想您可以使用^{} ,然后分配列
index
:另一个使用^{} 和
^{pr2}$dict
的解决方案,其中使用值交换密钥:通过传递要替换的值的映射列表来使用
replace
:相关问题 更多 >
编程相关推荐