[英]Multi-column to single column in 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
、 stack
和reset_index
。
首先轉換為Int64
將防止 child_Id 在堆疊過程中被轉換為浮點數。
(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.