【问题标题】:take a list of filters and return all possible combinations获取过滤器列表并返回所有可能的组合
【发布时间】:2020-09-30 15:41:48
【问题描述】:

我正在使用熊猫。我有一个过滤器列表,可用作 dataframe.loc[filter, :] 的一部分,例如。

df = pd.DataFrame(np.random.choice([True, False], size=[10,8]))

filter1 = df[1] == True
filter2 = df[5] == False
filter3 = (df[2] == True) & (df[7] == False)

filters = [filter1, filter2, filter3]

如何生成所有可能的过滤器组合的列表/字典? 例如。

{combination_1 : (filter_1),
combination_2 : (filter_1 & filter_2),
combination_3 : (filter_1 & filter_3),
combination_4 : (filter_1 & filter_2, & filter_3),
etc.}

这样我就可以遍历列表并对每个组合的数据框应用不同的函数。我想这样做,以便我可以根据过滤器的组合为真,以不同的颜色突出显示每一行。

我写了一个函数来生成一个十六进制字符串:

def hex_string(filter_1, filter_2, filter_3):
    bool_list = [filter_1, filter_2, filter_3]
    hex_list = ["FF" if value else "00" for value in bool_list]
    string = f"#{''.join(hexlist)}"
    return string

我的想法是我会用一个看起来像这样的函数来设置我的数据框的样式

def highlight_rows(dataframe):
    df = dataframe.copy()
    iterable = combination_generator_function(filter_list)

    for combination in iterable:
        df.loc[combination,:] = "background-color:{hex_string(combination)}"
    return df

df.style.apply(highlight_rows, axis=None)

我觉得这应该比我想象的要容易得多。是否可以在不输入每个单独的组合和相应的十六进制字符串的情况下执行此操作?

【问题讨论】:

    标签: python pandas styles


    【解决方案1】:

    这行得通吗:

    from itertools import combinations
    from functools import reduce
    
    filter_combos = [
        reduce(lambda x, y: x & y, combo)
        for i in range(1, len(filters) + 1)
        for combo in combinations(filters, i)
    ]
    

    举例说明:combinations(filters, 2) 为您提供元组

    (filter1, filter2), (filter1, filter3), (filter2, filter3)
    

    reduce(lambda x, y: x & y, combo) 通过 lambda 函数将 (filter1, filter2) 之类的元组“减少”为filter1 & filter2。 (reduce 从左到右累积工作,即它不仅适用于具有 2 个元素的元组。对于只有一个元素的元组,它只返回元素。)

    【讨论】:

    • 这正是我想要的。谢谢你。我遇到了一个小问题,'&' 没有按照我想要的方式组合两个过滤器。即我想要:``` filter1 = pandas.Series([True, False, True]) filter2 = pandas.Series([True, True, False]) reduce(lambda x, y: x&y, (filter1, filter2)) = pandas.Series([True, False, False]) ``` 我通过将系列转换为 numpy 数组来解决这个问题。但你的回答涵盖了我所问的一切。附言我对在堆栈溢出上发帖很陌生。在礼仪方面,除了支持你的回答,我还应该做些什么吗?
    • @Linden 很高兴我能帮上忙。重新“礼仪”:一切都好。
    【解决方案2】:

    我认为 itertools 在这里是一个很好的解决方案。

    import itertools  
    filters = [filter_1, filter_2, filter_3]  
    
    combinationList = []
    
    for i in range(len(filters)):  
        combinationList += list(itertools.permutations(filters,i+1))
    
    print(combinationList) #Probably cant print the filters, but combinationList is the list off all possible combinations from 1-3 filters per combination
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多