熊猫将数据框列中的列表与另一个数据框合并

时间:2020-03-19 11:51:28

标签: python pandas dataframe

我有2个数据框:

  emp_name      Iqama       Passport    DrivingLicence  OtheDocument
  Employee1     2852436985  EC6331777   5589492385      366791111
  Employee2     2315492339  EC6331841   2315492385      906792486

我需要根据LIST_VALUES列表中的内容,向第一个数据框添加一个新列,以显示第二个数据框的值。如果一个值在LIST_VALUES中重复,则仅在输出中显示一次。所以:

ID   LIST_VALUES
 1     [a,b,c]
 2     [a,n,t]
 3     [x]
 4     [h,h]


VALUE     MAPPING
 a         alpha
 b         bravo
 c         charlie
 n         november
 h         hotel
 t         tango
 x         xray

我尝试合并ID LIST_VALUES new_col 1 [a,b,c] alpha,bravo,charlie 2 [a,n,t] alpha,november,tango 3 [x] xray 4 [h,h] hotel ,但由于无法与列表中的元素合并,因此一直卡住。

pd.merge

这仅在LIST_VALUE仅具有1个元素的情况下起作用,因此在此示例ID 3中。我需要它在列表中有多个值的情况下起作用。

2 个答案:

答案 0 :(得分:0)

通过Series将列表推导与map一起使用,类似于字典,最后通过dict.fromkeys技巧和join值一起删除重复的值:

d = df2.set_index('VALUE')['MAPPING']
df1['new_col'] = [', '.join(dict.fromkeys([d[y] for y in x if y in d]).keys()) 
                                                               for x in df1['LIST_VALUES']]

print (df1)
   ID LIST_VALUES                 new_col
0   1   [a, b, c]   alpha, bravo, charlie
1   2   [a, n, t]  alpha, november, tango
2   3         [x]                    xray
3   4      [h, h]                   hotel

如果顺序对于新值而言并不重要,请使用set删除重复项:

d = df2.set_index('VALUE')['MAPPING']
df1['new_col'] = [', '.join(set([d[y] for y in x if y in d])) for x in df1['LIST_VALUES']]

print (df1)
   ID LIST_VALUES                 new_col
0   1   [a, b, c]   alpha, charlie, bravo
1   2   [a, n, t]  alpha, tango, november
2   3         [x]                    xray
3   4      [h, h]                   hotel

答案 1 :(得分:0)

一种方法是使用set_indexto_dict从第二个数据帧构建字典。然后使用嵌套列表推导,使用列表中的值查找字典:

d = df2.set_index('VALUE').MAPPING.to_dict()
# {'a': 'alpha', 'b': 'bravo', 'c': 'charlie', ...

df['new_col'] = [','.join([d[j] for j in i]) for i in df.LIST_VALUES]

print(df)

 ID LIST_VALUES                new_col
0   1   [a, b, c]   alpha,bravo,charlie
1   2   [a, b, c]   alpha,bravo,charlie
2   3         [x]                  xray
3   4      [h, h]           hotel,hotel

设置:

print(df2)

 VALUE   MAPPING
0     a     alpha
1     b     bravo
2     c   charlie
3     n  november
4     h     hotel
5     t     tango
6     x      xray

print(df)

   ID LIST_VALUES
0   1   [a, b, c]
1   2   [a, b, c]
2   3         [x]
3   4      [h, h]