簡體   English   中英

有沒有辦法使用pandas進行合並,其中一列是列表而另一列可能包含該列表中的元素?

[英]Is there a way to do a merge using pandas where one column is a list and another column might contain an element in that list?

現在我有兩個pandas數據幀:

第一個看起來像這樣:

id1 features
0   ['a', 'b']
1   ['c', 'd', 'e']
2   ['f']

第二個看起來像這樣:

id2 features other
224   'a'      3
264   'z'      3
277   'f'      3

我想使用pandas .merge()函數來結合兩者。 輸出應該如下所示:

id1 features other
0    'a'       3 
2    'f'       3

我知道可能有一種方法可以通過將第一個數據幀擴展為每個值的多行然后進行連接來實現,但我想知道是否有任何方法可以在不執行此操作的情況下執行此操作,或者最簡潔的方法是是。

我認為你實際上描述了最有效的方法: expanding the first dataframe into multiple rows per value then doing the join

我能看到的另一個選擇是迭代第二個選項。

df1 =\
id features
0   ['a', 'b']
1   ['c', 'd', 'e']
2   ['f']

df2 =\
id features other
0   'a'      3
1   'z'      3
2   'f'      3

做類似的事情:

features_in_df1 = set(np.flatten(df1.feature.values))

output = []
for _, row in df2.iterrows():
    if row['feature'] in features_in_df1:
        output.append(row)

df_merge = pd.concat(output)

IIUC

s=df1.merge(df2,on='id')
df2[[y in x for x , y in zip(s.features_x,s.features_y)]]
   id features  other
0   0        a      3
2   2        f      3

更新

df2[df2.features.isin(df1.features.sum())]
   id features  other
0   0        a      3
2   2        f      3

暫無
暫無

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

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