熊猫中的多列到单列



我有以下数据框:

parent          0        1      2   3
0   14026529    14062504     0      0   0
1   14103793    14036094     0      0   0
2   14025454    14036094     0      0   0
3   14030252    14030253  14062647  0   0
4   14034704    14086964     0      0   0

我需要这个:

parent_id   child_id
0   14026529   14062504
1   14025454   14036094
2   14030252   14030253  
3   14030252   14062647
4   14103793   14036094
5   14034704   14086964

这只是一个基本的例子,真正的交易可以有60多个孩子。

使用DataFrame.wherestackreset_index
首先将child_Id转换为浮点数Int64将防止在堆叠过程中将铸造为浮点数。

(df.astype('Int64').where(df.ne(0))
.set_index('parent')
.stack()
.reset_index(level=0, name='child'))

[出]

parent     child
0  14026529  14062504
0  14103793  14036094
0  14025454  14036094
0  14030252  14030253
1  14030252  14062647
0  14034704  14086964

最新更新