python - 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 多个孩子。
解决方案
使用和。DataFrame.where
_ 优先转换将防止在堆叠过程中将 child_Id 转换为浮点数
。stack
reset_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
推荐阅读
- amazon-web-services - 如何在 AWS LightSail Linux 实例上打开端口 25
- android - 从 Android 中的 Firebase 实时数据库中检索数据 - recyclerview
- list - 如何应用断言条件来更改列表?
- python - 如何从字符串而不是文档字符串运行 doctest 示例?为什么需要缩进?
- html - 为什么 iframe 不继承父级的样式?
- javascript - 如何在 socket.io 上获取 https
- azure - 如何在 Azure 数据工厂中获取管道文件夹路径?
- go - 在golang中获取数组的长度并将其存储在const中
- c# - 相机中的 UnassignedReferenceException
- android - 如何将屏幕分成两个区域,同时在中心有一个表格?