![](/img/trans.png)
[英]I have a all the rows with a particular column with lists. Select rows that does not contain atleast one element from the target list
[英]I have a pandas column with lists. Group rows that contains atleast one common element from same column
我有 pandas df 與 1 列與列表。 我想對至少有一個共同元素的所有列表進行分組。
Input Df :
>
Category
0 [IAB19, IAB81, IAB82]
1 [IAB25, IAB27]
2 [IAB19, IAB20]
3 [IAB22, IAB55, IAB56, IAB58]
4 [IAB81, IAB89]
5 [IAB82, IAB95]
我想知道 df['Category'] 中的任何代碼是否存在於 df['Category'] 的任何其他行中。
如果是的話,我想合並那些共享至少 1 個共同元素的列表。
預期 Output:
Category
0 [IAB19, IAB81, IAB82, IAB20, IAB89, IAB95]
1 [IAB25, IAB27]
2 [IAB22, IAB55, IAB56, IAB58]
有什么想法嗎?
這是一個隱藏的網絡問題,所以我們可以嘗試networkx
,但在此之前您可能需要將整個列表列pandas
explode
0.25
可用的功能)
import networkx as nx
df['Key']=df.index
df=df.explode('Category')
G=nx.from_pandas_edgelist(df, 'Category', 'Key')
l=list(nx.connected_components(G))
L=[dict.fromkeys(y,x) for x, y in enumerate(l)]
d={k: v for d in L for k, v in d.items()}
s=df.groupby(df.Key.map(d)).Category.apply(set)
s
Key
0 {IAB89, IAB82, IAB19, IAB95, IAB81, IAB20}
1 {IAB27, IAB25}
2 {IAB55, IAB56, IAB22, IAB58}
Name: Category, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.