【问题标题】:Filtering groups of empty keys: Filter function过滤空键组:过滤功能
【发布时间】:2020-07-10 00:17:57
【问题描述】:

问题:再次将filter(None, Dictionary) 转换为字典,同时过滤空键。

我正在尝试使用 Pandas DataFrame 处理一些实验室数据。考虑到前两列,我使用字典将这些数据分组;见以下代码:

d = {'col1': [1, 1, 1, 2], 'col2': [1, 2, 2, 2], 'col3': [1, 2 ,3, 4], 'col4': [2,1,1,1,], 'col5': [2,1,0,0], 'col6': [2,1,3,1]}
df = pd.DataFrame(data=d)
all_groups = {}
for i in df.col1.unique():
    for j in df.col2.unique():
        all_groups[f'{i}-{j}'] = df[(df.col1 == i) & (df.col2 == j)]

然后我想使用功能过滤器清除所有空键:filter(None, all_groups),这似乎是以下问题的答案:

[how to delete empty dict inside list of dictionary?

在文档中它说:

返回一个迭代器,该迭代器产生那些 function(item) 为 true 的可迭代项。如果 function 为 None,则返回为 true 的项。

我需要再次将此返回的序列转换为字典,但我不知道如何,因为它只是一个过滤器对象。

编辑 1:我尝试过使用 lambda 函数:

 hello = dict(filter(lambda x: len(x) != 0, all_groups))

ValueError: dictionary update sequence element #0 has length 12; 2 is required

【问题讨论】:

    标签: python dictionary filter


    【解决方案1】:

    在您的特定情况下,您可能会得到空的 lists 作为值,您可以这样做来过滤:

    1. 通过使用列表推导(这将创建一个新的字典)
        dictionary = {k:v for k, v in dictionary.items() if v}
    
    1. 通过使用 for 循环并删除具有空列表的键作为值(就地):
        for k, v in dictionary.items():
            if not v:
                dictionary.pop(k)
    
    1. 使用filter 内置方法(这将创建一个新的字典)
        dictionary = dict(filter(lambda x: x[1], dictionary.items()))
    

    如果您有一个值为pd.DataFrame 的字典,您可以过滤空数据框,例如:

    dict(filter(lambda x: not x[1].empty, all_groups.items()))
    

    输出:

    {'1-1':    col1  col2  col3  col4  col5  col6
     0     1     1     1     2     2     2,
     '1-2':    col1  col2  col3  col4  col5  col6
     1     1     2     2     1     1     1
     2     1     2     3     1     0     3,
     '2-2':    col1  col2  col3  col4  col5  col6
     3     2     2     4     1     0     1}
    

    【讨论】:

    • 我对第三个选项特别感兴趣。但是当我尝试 lambda 函数时,它对我不起作用。顺便说一句,你的回答说 Dataframe 的真值是模棱两可的。现在我可以使用: dict(filter(lambda x: len(x[1]) != 0, dictionary.items())) (如果你想修改你的答案)。非常感谢!!
    • @Nankin 您现在可以查看我的答案,如果此答案解决了您可以投票或接受的问题,谢谢!
    【解决方案2】:

    这个问题的另一个可能答案是,通过使用 lambda 函数:

    hello = dict(filter(lambda x: len(x[1]) != 0, all_groups.items()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      相关资源
      最近更新 更多