对于缺少值的数据框中的所有可能组的自定义分组

时间:2019-03-19 04:45:52

标签: python pandas numpy math combinations

我有一个代表一组产品的数据框。我需要在这些产品中找到所有重复的产品。如果产品具有相同的product_typecolorsize->,则它们是重复的。如果我没有问题,这将是一条简单的df.groupby('product_type','color','size')行:缺少某些值。现在,我必须找到所有可能在彼此之间重复的产品组。 这意味着某些元素可以出现在多个组中。

让我举例说明:

import pandas as pd


def main():
    df = pd.DataFrame({'product_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
                       'product_type': ['shirt', 'shirt', 'shirt', 'shirt', 'shirt', 'hat', 'hat', 'hat', 'hat', 'hat', 'hat', ],
                       'color': [None, None, None, 'red', 'blue', None, 'blue', 'blue', 'blue', 'red', 'red', ],
                       'size': [None, 's', 'xl', None, None, 's', None, 's', 'xl', None, 'xl', ],
                       })
    print df   

if __name__ == '__main__':
    main()

此数据框:

enter image description here

我需要这个结果-每个可能的组的列表(可能只有最大的超级组):

![enter image description here

例如,让我们用id=1来做“衬衫” 该产品没有颜色或尺寸,因此他可能与2号衬衫(尺寸为“ s”但没有颜色)和4号衬衫(颜色为“红色”但可以)一起出现在可能的“重复组”中没有大小)。因此,这三件衬衫(1,2,4)可能是相同颜色“红色”和尺寸“ s”的副本。

我试图通过遍历缺失值的所有可能组合来实现它,但感觉错了又复杂。

有没有办法得到想要的结果?

1 个答案:

答案 0 :(得分:0)

这个发现所有组合的问题可能是指数复杂的;

from itertools import product

def get_possible_combinations(df, columns=['size',  'product_type', 'color']):
    col_vals = []
    for col in columns:
        col_vals.append(df.loc[~df.loc[:, col].isnull(), col].unique().tolist())
    for comb in product(*col_vals):
        df_ = df.copy()
        for val, col in zip(comb, columns):
            df_.loc[:, col].fillna(val, inplace=True)
        yield df_.groupby(columns)

因此,我们可以将此功能应用于df

resulting_groups = []
for g in get_possible_combinations(df):
    sorted_groups = [ind.tolist() for a, ind in g.groups.items()]
    resulting_groups.append(sorted_groups)

resulting_groups = sum(resulting_groups, [])
sorted(list(set(map(tuple, resulting_groups))), key=len, reverse=True)
  

[(5,6,7),(0,2,3),(0,1,3),(0,1,4),(0,2,4),(5,9),   (6,7),(6,8),(5,7),(9,10),(1,),(2,),(8,),(3,),(9,),   (4,),(10,),(5,),(7,)]

这与您要寻找的几乎相同。