如何在Pandas列的List中提取Dictionary值?

时间:2019-01-23 06:05:47

标签: python pandas list dictionary

 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'

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

1 个答案:

答案 0 :(得分:1)

您要从循环访问列表,以访问字典使用:

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

['Raj', 'mac']

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

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

编辑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']