2017-04-15 165 views
0

返回ID我有一個有索引和列表的列,看起來大熊貓據幀df1,如:名單Python的熊貓數據幀校驗列,並從另一個數據幀

index IDList 
0 [1,3,5,7] 
1 [2,4,5,8] 
2 [6,8,9] 
3 [1,2] 

我有另一隻大熊貓數據幀df2這有NEWID作爲索引和列表的列,看起來像這樣:

NewID IDList 
1  [3] 
2  [4,5] 
3  [1,7] 
4  [2] 
5  [9,3] 
6  [8] 
7  [6] 

我需要做的是,如果任何df1.IDList項目的df2.IDList存在,則返回相關名單。

,返回的d1數據框看起來像:

index IDList  NewID 
0  [1,3,5,7] [3,1,2,3,5] 
1  [2,4,5,8] [4,2,2,6] 
2  [6,8,9]  [7,6,5] 
3  [1,2]  [3,4] 

編輯:注意,在df2可以有ID在IDList表出現在多個行(見ID 3從df1.IDList和其中ID 3顯示在df2行1和5)

我在想某種np.where結合「any」和列表理解的聲明?但不確定如何申請IDListdf1,看看整個df2.IDList。也許某種.stack()?或.melt()?這將是很容易與DF2的VLOOKUP電子表格...

幫助讚賞...

回答

1
# expand and map ids from IDList to NewID 
flat_ids = pd.DataFrame({ 
    "NewID": pd.np.repeat(df2.NewID, df2.IDList.str.len().tolist()), 
    "IDList": [x for l in df2.IDList for x in l] 
}).set_index("IDList").NewID 

# extract ids from flat ids using loc 
df1['NewID'] = df1['IDList'].map(lambda x: flat_ids.loc[x].tolist()) 

enter image description here

+0

拍,有可能是從DF2的列IDList表重複。我會編輯 – clg4

+0

好的。我弄錯了。如果* IDList *列中有重複項,這也應該起作用。 – Psidom

+0

獲取:TypeError:repeat()需要2個位置參數,但有3個被給出 – clg4