【发布时间】: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)
我觉得这应该比我想象的要容易得多。是否可以在不输入每个单独的组合和相应的十六进制字符串的情况下执行此操作?
【问题讨论】: