亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在數據框中保留直接父子 ID 對

僅在數據框中保留直接父子 ID 對

弒天下 2023-03-16 16:37:16
我有以下數據框:   id_parent  id_child0       1100      10901       1100      10802       1100      10703       1100      10604       1090      10805       1090      10706       1080      1070我只想保持直接父子連接。示例:1100 有 3 個連接,但只保留 1090,因為 1080 和 1070 已經是 1090 的子節點。此示例 df 僅包含 1 個樣本,df 由多個父/子集群組成。因此,輸出應如下所示:   id_parent  id_child0       1100      10901       1090      10802       1080      10703       1100      1060示例代碼:import pandas as pd#create sample input df_input = pd.DataFrame.from_dict({'id_parent': {0: 1100, 1: 1100, 2: 1100, 3: 1100, 4: 1090, 5: 1090, 6: 1080}, 'id_child': {0: 1090, 1: 1080, 2: 1070, 3: 1060, 4: 1080, 5: 1070, 6: 1070}})#create sample outputdf_output = pd.DataFrame.from_dict({'id_parent': {0: 1100, 1: 1090, 2: 1080, 3: 1100}, 'id_child': {0: 1090, 1: 1080, 2: 1070, 3: 1060}})我目前的方法是基于這個問題:Creating dictionary of parent child pairs in pandas dataframe 但也許有一種簡單干凈的方法可以解決這個問題而不依賴于額外的非標準庫?
查看完整描述

2 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

這對我有用:


# First: group df by child id

grouped  = df_input.groupby(['id_child'], as_index=True).apply(lambda a: a[:])

# Second: Create a new output dataframe

OUTPUT = pd.DataFrame(columns=['id_parent','id_child'])

# Third: Fill it with the unique childs ids and the minimun id for their parent in case of more than one. 

for i,id_ch in enumerate(df_input.id_child.unique()):

    OUTPUT.loc[i] = [min(grouped.loc[id_ch].id_parent), id_ch]


查看完整回答
反對 回復 2023-03-16
?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

我可以使用得到結果drop_duplicates


In [6]: df

Out[6]:

   id_parent  id_child

0       1100      1090

1       1100      1080

2       1100      1070

3       1090      1080

4       1090      1070

5       1080      1070


In [9]: df.drop_duplicates(subset=['id_parent']).reset_index(drop=True)

Out[9]:

   id_parent  id_child

0       1100      1090

1       1090      1080

2       1080      1070


查看完整回答
反對 回復 2023-03-16
  • 2 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號