首页 > 解决方案 > Pandas 中的多列到单列

问题描述

我有以下数据框:

    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 多个孩子。

标签: pythonpandasdataframe

解决方案


使用和。DataFrame.where_ 优先转换将防止在堆叠过程中将 child_Id 转换为浮点数 。stackreset_index
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

推荐阅读