【发布时间】:2021-01-15 10:21:35
【问题描述】:
我使用 python 已经有一段时间了,但在我的一生中,我找不到将包含嵌套字典列表的数据框中的列转换为仅包含值的集合的解决方案。第一行是我的数据框中的一行示例:
{'source': 'test', 'host': 'server1', 'event': 'metric', 'time': 1297361370, 'fields': {'_value': 0.0, 'metric_name': 'cloud_unit_used', 'enabled': 1, 'aid': 1283541, 'savedEvent': 0, 'accountGroupName': 'AG1', 'testId': 944111, 'testName': 'https://test.com - server1', 'testType': 'http-server', 'interval': 900, **'groups': [{'name': 'Asia Pacific', 'groupId': 11111, 'builtin': 0}, {'name': 'EMEA', 'groupId': 22222, 'builtin': 0}, {'name': 'Switzerland', 'groupId': 33333, 'builtin': 0}, {'name': 'Americas', 'groupId': 44444, 'builtin': 0}]**, 'server': '', 'test_sharing': 'Test Owner', 'url': 'https://server1', 'httpTimeLimit': 5.0, 'pageLoadTimeLimit': '', 'ftpTimeLimit': '', 'agentId': 55555.0, 'agentName': 'AGN1', 'agentType': 'Enterprise', 'countryId': 'GB'}}
该行包含标记为组的列。 Groups 是嵌套字典的列表:
'groups': [{'name': 'Asia Pacific', 'groupId': 11111, 'builtin': 0}, {'name': 'EMEA', 'groupId': 22222, 'builtin': 0}, {'name': 'Switzerland', 'groupId': 33333, 'builtin': 0}, {'name': 'Americas', 'groupId': 44444, 'builtin': 0}]
我只是想将组转换为仅包含嵌套字典中的名称值的集合:
'groups': {'Asia Pacific','EMEA','Switzerland','Americas'}
请注意,名称值的数量可能会有所不同。因此,在其他行中,组可能包含 1 个或多个名称。
结果行示例:
{'source': 'test', 'host': 'server1', 'event': 'metric', 'time': 1297361370, 'fields': {'_value': 0.0, 'metric_name': 'cloud_unit_used', 'enabled': 1, 'aid': 1283541, 'savedEvent': 0, 'accountGroupName': 'AG1', 'testId': 944111, 'testName': 'https://test.com - server1', 'testType': 'http-server', 'interval': 900, **'groups': {'Asia Pacific','EMEA','Switzerland','Americas'}**, 'server': '', 'test_sharing': 'Test Owner', 'url': 'https://server1', 'httpTimeLimit': 5.0, 'pageLoadTimeLimit': '', 'ftpTimeLimit': '', 'agentId': 55555.0, 'agentName': 'AGN1', 'agentType': 'Enterprise', 'countryId': 'GB'}}
有人可以帮我找到解决方案吗?非常感谢大家!
【问题讨论】:
-
您希望该集合仅包含字典的值吗?还是键和值?还是只是钥匙?
-
提供了一个
listofdict对象(groups),s = {d['name'] for d in groups}将从每个dict中提取与键'name'关联的所有dict值到@987654332 @分配给变量s。使用提供的示例进行测试并获得预期的输出。不是 100% 关于如何在df更新的上下文中最好地实现这一点 -df.apply()? -
您好,感谢您对 Mushif 的回复……只有价值观。
标签: python list dataframe dictionary set