[英]Converting a list of nested dictionaries into a set inside of a dataframe
我已经使用 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'}}
有人可以帮我找到解决方案吗? 非常感谢大家!
这是通用代码:
为了
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=set([i['name'] for i in groups])
print(groups)
{'Americas', 'Switzerland', 'EMEA', 'Asia Pacific'}
如果您需要为数据框调整代码,请提供 df 构造函数
我要感谢大家的帮助..我找到了一个有效的解决方案:
for row in merged_df.itertuples():
merged_df.at[row.Index, 'labels'] = list(set([i['name'] for i in row.groups]))
merged_df.drop('groups', inplace=True, axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.