简体   繁体   English

如何将 python 中的字典列表拆分为具有值名称的列?

[英]How do I split a list of dicts in python into columns with names of the values?

I'm trying to build some custom reporting on Asana tasks using their API / Python 3.9.我正在尝试使用他们的 API / Python 3.9 构建一些关于 Asana 任务的自定义报告。

The API has parameters to call 'custom_fields' but returns these custom fields as a nested list. API 具有调用“custom_fields”的参数,但将这些自定义字段作为嵌套列表返回。

Specifically, when I parse the result into a pandas data frame, the column with the custom fields looks like this:具体来说,当我将结果解析为 pandas 数据帧时,包含自定义字段的列如下所示:

[
{'gid': '123', 'name': 'Priority', 'display_value': 'abc'}, 
{'gid': '456', 'name': 'Estimated Minutes', 'display_value': 'abc'}, 
{'gid': '789', 'name': 'Status 1', 'display_value': 'abc'}, 
{'gid': 'a12', 'name': 'Status 2', 'display_value': 'abc'}, 
{'gid': 'b24', 'name': 'Status 3', 'display_value': 'abc'}, 
{'gid': '745', 'name': 'Status', 'display_value': 'abc'}
]

I'd like to split this into columns such that:我想把它分成几列,这样:

  • the column names are the 'name' attribute列名是“名称”属性
  • the column values are the 'display_value' attribute列值是“display_value”属性

Note that different rows in the data frame may have different varieties of the list / dict above.请注意,数据框中的不同行可能具有上述列表/字典的不同种类。 eg, some may have all the columns, some may have more, some may have fewer.例如,有些可能有所有列,有些可能有更多,有些可能有更少。 Ultimately I'd like the end-state data frame to have columns that correspond to all the unique attributes in the whole data frame.最终,我希望最终状态数据框具有对应于整个数据框中所有唯一属性的列。

Thanks!谢谢!

It's not clear what you're asking... is this what you want?不清楚你在问什么……这是你想要的吗?

data = [
{'gid': '123', 'name': 'Priority', 'display_value': 'abc'}, 
{'gid': '456', 'name': 'Estimated Minutes', 'display_value': 'abc'}, 
{'gid': '789', 'name': 'Status 1', 'display_value': 'abc'}, 
{'gid': 'a12', 'name': 'Status 2', 'display_value': 'abc'}, 
{'gid': 'b24', 'name': 'Status 3', 'display_value': 'abc'}, 
{'gid': '745', 'name': 'Status', 'display_value': 'abc'}
]

df = pd.DataFrame(data)
df = df.set_index('name').T
print(df)

Output: Output:

name          Priority Estimated Minutes Status 1 Status 2 Status 3 Status
gid                123               456      789      a12      b24    745
display_value      abc               abc      abc      abc      abc    abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM