如何从Pandas列的列表中提取字典值?

2024-06-06 17:54:23 发布

您现在位置:Python中文网/ 问答频道 /正文

 Assigne(column name)
[{'id': 2342343, 'username': 'Raj', 'color': '#08c7e0', 'profilePicture': None}]
[{'id': 764665, 'username': 'mac', 'color': '#08c7e0', 'profilePicture': None}]

name = [d.get('username') for d in df.assigne]
print (name)

AttributeError: 'list' object has no attribute 'get'

任何建议都会有帮助的,谢谢。在


Tags: nameinnoneiddfforgetmac
1条回答
网友
1楼 · 发布于 2024-06-06 17:54:23

您正在从循环访问列表,要访问字典,请使用:

name = [d[0].get('username') for d in df.assigne]
print (name)

['Raj', 'mac']

编辑1:如果行包含空列表,请使用:

^{pr2}$

编辑2:如果列表中有多个词典:

df = pd.DataFrame([[[{'id':2342343, 'username':'Raj', 'color':'#08c7e0', 'profilePicture':None}]],
                   [[{'id':764665, 'username':'mac', 'color':'#08c7e0', 'profilePicture':None}]],
                   [[{'id':2342343, 'username':'Raj', 'color':'#08c7e0', 'profilePicture':None}, 
                     {'id':2342343, 'username':'mac', 'color':'#08c7e0', 'profilePicture':None}]],
                   [[]],
                   [[{'id':2342343, 'username':'sand', 'color':'#08c7e0', 'profilePicture':None}]]], 
                  columns=['Assigne'])

name = [x.get('username')  for d in df.Assigne if d for x in d]

print(name)
['Raj', 'mac', 'Raj', 'mac', 'sand']

相关问题 更多 >