栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从pandas数据框父子表获取父的所有后代

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从pandas数据框父子表获取父的所有后代

这应该在您想要的两列中返回父级和子级ID:

import pandas as pdimport numpy as npimport itertoolsdf = pd.Dataframe(    {        'parent_id': [3111, 2010, 3000, 1000, 4023, 3011, 3033, 5010, 3011, 3102, 2010, 4023, 2110, 2100, 1000, 5010, 2110, 1000, 5010, 3033],        'child_id': [4321, 3102, 4023, 2010, 5321, 4200, 4113, 6525, 4010, 4001, 3011, 5010, 3000, 3033, 2110, 6100, 3111, 2100, 6016, 4311]    })def get_child_list(df, parent_id):    list_of_children = []    list_of_children.append(df[df['parent_id'] == parent_id]['child_id'].values)    for i_, r_ in df[df['parent_id'] == parent_id].iterrows():        if r_['child_id'] != parent_id: list_of_children.append(get_child_list(df, r_['child_id']))    # to flatten the list     list_of_children =  [item for sublist in list_of_children for item in sublist]    return list_of_childrennew_df = pd.Dataframe(columns=['parent_id', 'list_of_children'])for index, row in df.iterrows():    temp_df = pd.Dataframe(columns=['parent_id', 'list_of_children'])    temp_df['list_of_children'] = pd.Series(get_child_list(df, row['parent_id']))    temp_df['parent_id'] = row['parent_id']    new_df = new_df.append(temp_df)print new_df


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386886.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号