首页 > 解决方案 > 使用 Pandas 在 Python 中将 API 响应数据解析为数据框

问题描述

我正在尝试解析从 API 调用到 ERP 系统的数据。我想将这些数据作为 Pandas 的数据框引入,以便我可以使用这些数据。每次尝试使用 json_string / json_dumps 或 DataFrame.from_dict() 解析它都不适合我。

我的原始数据文件如下所示:

Type:        dict
String form: {0: [{'productID': 144194, 'name': 'XXXtentacion, ?,        LP', 'code': '1039907', 'code2': '1210672',  <...> Field4Title': 'Format Notes', 'extraField4ID': 0, 'extraField4Code': '', 'extraField4Name': ''}]}
    Length:      1
    Docstring:  
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)

我得到的最接近的是:

pd.DataFrame.from_dict(data)

返回:

                                                    0
0   {'productID': 144194, 'name': 'XXXtentacion, ?...
1   {'productID': 131605, 'name': 'Sufjan Stevens ...
2   {'productID': 143699, 'name': 'Sufjan Stevens ...
3   {'productID': 134277, 'name': 'Sufjan Stevens ...
4   {'productID': 135151, 'name': 'Sufjan Stevens ...
5   {'productID': 145844, 'name': 'Spearhead, Home...

但我想要的是键是列标题(即'productID'应该是第一个列标题。

我刚刚开始使用 Python,因此非常感谢任何帮助。我环顾了类似的主题,似乎找不到解决方案。

标签: pythonpandas

解决方案


假设您的数据结构为 Dict(key1: List(Dict(...)), key2: ...)

尝试

data = {d:data[d][0] for d in data}
pd.DataFrame.from_dict(data)

推荐阅读