我想將兩個串列串列與資料框列進行比較。
list1=[[r2,r4,r6],[r6,r7]]
list2=[[p4,p5,p8],[p86,p21,p0,p94]]
資料集:
| 擺脫 | PID | 價值 |
|---|---|---|
| r2 | p0 | 香蕉 |
| r2 | p4 | 巧克力 |
| r4 | p89 | 蘋果 |
| r6 | p5 | 牛奶 |
| r7 | p0 | 面包 |
輸出:
[[chocolate,milk],[bread]]
由于r2和p4出現在list1[0]和資料集中list2[0]的同一行中,所以chocolate必須存盤。同樣r6,并且p5出現在兩個串列中的相同位置和資料集中的同一行中,milk必須存盤。
uj5u.com熱心網友回復:
回答
result = []
for l1, l2 in zip(list1, list2):
res = df.loc[df["rid"].isin(l1) & df["pid"].isin(l2)]["value"].tolist()
result.append(res)
[['chocolate', 'milk'], ['bread']]
解釋
zip將合并兩個串列,相當于
for i in range(len(list1)):
l1 = list1[i]
l2 = list2[i]
df["rid"].isin(l1) & df["pid"].isin(l2)將條件與and operator&
附注
- list1 和 list2 的長度必須相等,否則,
zip將忽略較長串列的其余元素。
uj5u.com熱心網友回復:
你可以這樣做:
from itertools import product
df = pd.DataFrame({'rid': {0: 'r2', 1: 'r2', 2: 'r4', 3: 'r6', 4: 'r7'},
'pid': {0: 'p0', 1: 'p4', 2: 'p89', 3: 'p5', 4: 'p0'},
'value': {0: 'banana', 1: 'chocolate', 2: 'apple', 3: 'milk', 4: 'bread'}})
list1 = [['r2','r4','r6'],['r6','r7']]
list2 = [['p4','p5','p8'],['p86','p21','p0','p94']]
# Generate all possible associations.
associations = (product(l1, l2) for l1, l2 in zip(list1, list2))
# Index for speed and convenience of the lookup.
df = df.set_index(['rid', 'pid']).sort_index()
output = [[df.loc[assoc, 'value'] for assoc in assoc_list if assoc in df.index]
for assoc_list in associations]
print(output)
[['chocolate', 'milk'], ['bread']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471062.html
下一篇:將短語串列轉換為相應的數字
