gpt4 book ai didi

python - 组合行中的字典列表,然后从中提取字符串以形成新行

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:36 26 4
gpt4 key购买 nike

我有一个数据框,其中一列包含数据类型、列表、字典和缺失值的组合,如下所示:

df['category']

0 [{'id': '3120', 'name': '1109 Neurosciences'}, {'id': '2019', 'name': '1344 Statistics'}]
1 [{'id': '9572', 'name': '1234 Mathematics'}, {'id': '2345', 'name': '1307 Biology'}, {'id': '3456', 'name': '9876 Computer Science'}]
2 NaN
3 [{'id': '2378', 'name': '1398 Computer Vision'}]

我想将所有行组合在一起并使其成为一个新行,如果可能的话只包含一部分数据。

输出如下:

df_new['category']

0 [Neurosciences, Statistics, Mathematics, Biology, Computer Science, Computer Vision]

非常感谢你们!

最佳答案

这应该可行

import itertools

def extract_name(l):
try:
return [''.join([i for i in _['name'] if not i.isdigit()]).strip() for _ in l]
except:
return

# apply the extract_name function and convert output to list
classes = df['category'].apply(extract_name).dropna().values.tolist()

# flatten the list
[*itertools.chain(*classes)]

输出:

['Neurosciences',
'Statistics',
'Mathematics',
'Biology',
'Computer Science',
'Computer Vision']

关于python - 组合行中的字典列表,然后从中提取字符串以形成新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com