2017-04-15 184 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