簡體   English   中英

Pandas 將數據幀列中的列表與另一個數據幀合並

[英]Pandas merge a list in a dataframe column with another dataframe

我有 2 個數據框:

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

我需要向第一個數據框中添加一個新列,該列根據 LIST_VALUES 列表中的內容顯示第二個數據框中的 VALUES。 如果 LIST_VALUES 中的值重復,則只在輸出中顯示一次。 所以:

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但我一直被卡住,因為我無法與列表中的元素合並。

df_new = df1.merge(df2, how='left', left_on='LIST_VALUES', right_on='VALUES') 

這僅適用於 LIST_VALUE 只有 1 個元素的情況,因此在此示例 ID 3 中。我需要它在列表中有多個值的情況下工作。

使用列表理解與地圖Series像字典一樣的方法,最后刪除重復值由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

一種方法是使用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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM