python - 在条件之后迭代地为 df.column 赋值
问题描述
我有一个数据框,其中包含一个包含列表的列。该列表可以是空白的,也可以在其第一个条目处包含字典。
index labels
0 []
1 [{'id': 1178423440, 'node_id': 'MDU6TGFiZWwxMT...
2 [{'id': 1178425127, 'node_id': 'MDU6TGFiZWwxMT...
3 [{'id': 1213670757, 'node_id': 'MDU6TGFiZWwxMj...
4 [{'id': 1178430857, 'node_id': 'MDU6TGFiZWwxMT...
我想用 key = 'id' 代替列表分配值(对于每个条目)。这是我所做的。
for i in issues['labels']:
if not i: continue
i=i[0]['id']
我意识到这是分配值,因为 df 保持不变(即使它运行)。我究竟做错了什么?
预期输出:
index labels
0
1 1178423440
2 1178425127
3 1213670757
4 1178430857
编辑:
比如说,如果每行内的列表中的索引 0 包含 2 个或更多字典,就像这样
[{'id': 1497192821, 'node_id': 'MDU6TGFiZWwxNDk3MTkyODIx', 'url': 'https://api.github.com/repos/chef/chef/labels/Focus:%20knife%20bootstrap', 'name': 'Focus: knife bootstrap', 'color': '92ef98', 'default': False, 'description': ''}, {'id': 1178425127, 'node_id': 'MDU6TGFiZWwxMTc4NDI1MTI3', 'url': 'https://api.github.com/repos/chef/chef/labels/Platform:%20Windows', 'name': 'Platform: Windows', 'color': 'a2c429', 'default': False, 'description': ''},
{'id': 1178435805, 'node_id': 'MDU6TGFiZWwxMTc4NDM1ODA1', 'url': 'https://api.github.com/repos/chef/chef/labels/Status:%20Waiting%20on%20Contributor', 'name': 'Status: Waiting on Contributor', 'color': '0052cc', 'default': False, 'description': 'A pull request that has unresolved requested actions from the author.'},
{'id': 525658991, 'node_id': 'MDU6TGFiZWw1MjU2NTg5OTE=', 'url': 'https://api.github.com/repos/chef/chef/labels/Type:%20Bug', 'name': 'Type: Bug', 'color': 'bfe5bf', 'default': False, 'description': "Doesn't work as expected."}]
如何解析 key='id' 的所有值并将其附加到labels
同一位置的列中?
预期操作:
index labels
0 [] #has no entries
1 [1178423440,1178435805,525658991] # has 3 dictionaries with 3 different id values (values with key='id)
2 [1178425127,132131,13213] # slly, has 2 id values
3 [1389810] # has one id value
解决方案
如果不匹配,则使用str
此处的方法进行正确工作,则返回NaN
:
issues['labels'] = issues['labels'].str[0].str.get('id')
如果需要具有缺失值的整数,请使用整数 nan:
issues['labels'] = issues['labels'].str[0].str.get('id').astype('Int64')
编辑:如果每个字典都有id
使用:
issues['labels'] = issues['labels'].apply(lambda x: [y['id'] for y in x])
如果可能的话,一些 dict 没有id
添加测试:
issues['labels'] = issues['labels'].apply(lambda x: [y['id'] for y in x if 'id' in y])
推荐阅读
- typescript - 使用 Angular 6 中的自定义管道进行排序
- python - Better method to iterate over 3 lists
- javascript - react form onChange to update state
- jenkins - 强制 Jenkins 在同一个节点上运行触发的作业
- java - Problem with Java GridLayout and adding Buttons
- node.js - Check if all elements present in an array
- python - Python: How do I use variables in a string pulled from a json file?
- php - 在 localhost 上建立 WebSocket 连接
- python-3.x - rpyc,如何处理断开连接和重新连接
- node.js - 共享 NodeJS 和浏览器库?DOMParser => dom-parser 和 createNodeIterator => dom-node-iterator