2017-02-17 80 views
1

我正在處理多個具有多對多關係的表格。什麼是最有效的方式來轉換這些數據,以確保類別列是唯一的,並且所有相應的單位都合併成一行?將多行的值合併爲一行

category unit 
A01   97337 
A01   97333 
A01   97334 
A01   97343 
A01   26223 
A01   26226 
A01   22722 
A01   93397 
A01   97332 
A01   97342 
A01   97369 
A01   97734 
A01   97332 
P76   97343 
P76   26223 
P76   27399 
P76   27277 
P76   27234 
P76   27297 
P76   27292 
P76   22723 
P76   93622 
P76   27343 
P76   27234 
P98   97337 

向該:

每個類別
category category_units 
A01  97337, 97333, 97334, 97343, 26223, 26226, 22722, 93397, 97332, 97342, 97369, 97734, 97332 
P76  97343, 26223, 93622, 99733, 27399, 27277, 27234, 27297, 27292 
P98  97337 

一行(作爲主鍵),其中每個相應的單元被連接成一個單一的柱,用由逗號分隔的值。

我會加入這個數據回到另一個事實表,最終最終用戶會過濾category_units它'包含'一些值,所以它會拉出所有與該值相關聯的行。

回答

3

您可以使用groupbyapplyjoin,如果unit列數字是必要的強制轉換爲string

df1 = df.groupby('category')['unit'] 
     .apply(lambda x: ', '.join(x.astype(str))) 
     .reset_index() 
print (df1) 
    category            unit 
0  A01 97337, 97333, 97334, 97343, 26223, 26226, 2272... 
1  P76 97343, 26223, 27399, 27277, 27234, 27297, 2729... 
2  P98            97337 

另一種解決方案與第一投射:

df.unit = df.unit.astype(str) 
df1 = df.groupby('category')['unit'].apply(', '.join).reset_index() 
print (df1) 
    category            unit 
0  A01 97337, 97333, 97334, 97343, 26223, 26226, 2272... 
1  P76 97343, 26223, 27399, 27277, 27234, 27297, 2729... 
2  P98            97337 
+0

酷,工程巨大。由於我的一些連接(很多中間表)的性質,我的最終結果在一行中有一些重複。例如,類別= A01,單位= 97337,26223,97337。有沒有一種方法可以乾淨地刪除行級重複?我正在考慮使用.str.split(),但我不知道如何只保留每行的唯一值。 – trench

+1

您可以使用'set'或'unique',如'df1 = df.groupby('category')['unit'] .apply(lambda:','.join(x.unique()。astype(str )))或'df1 = df.groupby('category')['unit'] .apply(lambda x:','.join(set(x.astype(str))))' – jezrael

+0

這一切都奏效完美。我實際上必須應用它幾個多對多的表格,結果正是我想要的。謝謝 – trench