2017-02-17 141 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