我想在下面兩列的單元格中洗掉任何重復的單詞或單詞組,并且仍然在每個單詞或單詞組之間保持“,”。我嘗試了一個函式,該函式使用return (' , '.join(dict.fromkeys(text.split())))然后將其應用于function每一列,但它分隔了我不想分隔的單詞并添加了不需要的逗號(例如three four,不應該用逗號分隔)。該解決方案將應用于 和 中的更多col2行col3。
代碼:
df0 = pd.DataFrame(data ={'col1':[123,123,123],'col2':['one , two , three four', 'two','three four'],
'col3':['many numbers , another number', 'number','another number , number']})
df0['col2'] = df0.groupby(['col1'])['col2'].transform(lambda x : ' , '.join(x))
df0['col3'] = df0.groupby(['col1'])['col3'].transform(lambda x : ' , '.join(x))
df0 = df0.drop_duplicates()
df0
電流輸出:
col1 col2 col3
0 123 one , two , three four , two , three four many numbers , another number , number , another number , number
所需的輸出:
col1 col2 col3
0 123 one , two , three four many numbers , another number , number
uj5u.com熱心網友回復:
.transform()將保持原始組中存在的行數。由于您似乎正在使用.drop_duplicates()資料框來否定這一點,因此最好.agg()首先使用。
從那里開始,解決方案與您的解決方案類似,但使用set而不是dict(類似,但更簡單)并將您的分隔符傳遞' , '回split.
假設元素的最終順序無關緊要,這將起作用:
delim = ' , '
df0 = df0.groupby('col1', as_index = False)[['col2', 'col3']].agg(lambda s: ' , '.join(set(delim.join(s).split(delim))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431724.html
