首页 > 解决方案 > 在条件之后迭代地为 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

标签: pythonpandas

解决方案


如果不匹配,则使用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])

推荐阅读