【发布时间】: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