[英]Group by dataframe in python and concat strings on multiple columns
[英]Concat strings in multiple columns without duplicates
我有如下數據:
# df
Col1 Col2 Col3 Col4
AAA
AAA AAA BBB
AAA CCC
我想連接它們而不重復。
Col1 Col2 Col3 Col4 COMBINE
AAA AAA
AAA AAA BBB AAA/BBB
AAA CCC AAA/CCC
我試過的代碼:
df["COMBINE"] = df[df.filter(regex='^Col',axis=1).columns].apply(lambda x: '/'.join(pd.unique(x)),axis=1)
但我得到了:
Col1 Col2 Col3 Col4 COMBINE
AAA AAA/
AAA AAA BBB AAA/BBB/
AAA CCC AAA/CCC/
嘗試:
df['Combine'] = df.apply(lambda x: '/'.join(x.dropna().unique()), axis=1)
注意:如果你有空字符串而不是NaN
,那么做: df.replace('', np.nan).apply(...)
。
輸出:
Col1 Col2 Col3 Col4 Combine
0 AAA None None NaN AAA
1 AAA AAA BBB NaN AAA/BBB
2 AAA CCC None NaN AAA/CCC
您可以在以下時間進行清理:
df['Combine'] = df.fillna('').apply('/'.join, axis=1).str.replace('/+(?=/|$)', '', regex=True)
工作原理:如果一個或多個/
后跟另一個/
或行尾 -> 刪除
[AAA, None, None, NaN] -> [AAA, '', '', ''] -> AAA/// -> AAA
輸出:
Col1 Col2 Col3 Col4 Combine
0 AAA None None NaN AAA
1 AAA AAA BBB NaN AAA/AAA/BBB
2 AAA CCC None NaN AAA/CCC
發生這種情況是因為您的列中有空字符串,您可以更改如下代碼並獲得所需的內容:
>>> df.replace('', np.nan, inplace=True)
>>> df["COMBINE"] = df[df.filter(regex='^Col',axis=1).columns].apply(lambda x: '/'.join(x.dropna().unique()),axis=1)
>>> df
Col1 Col2 Col3 Col4 COMBINE
AAA AAA
AAA AAA BBB AAA/BBB
AAA CCC AAA/CCC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.