我有一個這樣的資料框(注意:C 是 A 中值的計數):
A B C
ex, one, two, three X1 4
ex, one, two X2 3
one, two, four X3 3
ex, three X4 2
four, ex X5 2
four, one X6 2
我想洗掉 A 列中的值是 A 列中另一個值的子集的所有行。所以結果應該如下所示
A B C
ex, one, two, three X1 4
one, two, four X3 3
four, ex X5 2
我嘗試了以下方法:
dataframe[np.sum(np.array([[y in x for x in dataframe.A.values] for y in dataframe.A.values]),1)==1]
但是,這只會過濾掉具有相同順序的值,例如“ex,一,二”和“ex,一,二,三”,而不是“ex,二,三”。
尋求幫助:)
uj5u.com熱心網友回復:
IIUC,您可以將列轉換為集合,然后,假設通過減少 C 進行先前排序,您可以檢查每個集合是否是任何先前集合的子集。最后,切片資料框:
l = [set(s.split(', ')) for s in df['A']]
# [{'ex', 'one', 'three', 'two'},
# {'ex', 'one', 'two'},
# {'four', 'one', 'two'},
# {'ex', 'three'},
# {'ex', 'four'},
# {'four', 'one'}]
notsub = [not any(s.issubset(x) for x in l[:i]) for i,s in enumerate(l)]
# [True, False, True, False, True, False]
df2 = df[notsub]
輸出:
A B C
0 ex, one, two, three X1 4
2 one, two, four X3 3
4 four, ex X5 2
如果可能的話,重復的集合
在這種情況下,您還需要與大小相等的集合進行比較,最好是使用frozensetand pandas.Series.duplicated:
l = [frozenset(s.split(', ')) for s in df['A']]
notsub = [not any(s.issubset(x) for x in l[:i]) for i,s in enumerate(l)]
df2 = df[notsub & ~pd.Series(l).duplicated()]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/434726.html
