【问题标题】:The error "AttributeError: 'list' object has no attribute 'values'" appears when I try to convert JSON to Pandas Dataframe当我尝试将 JSON 转换为 Pandas Dataframe 时出现错误“AttributeError: 'list' object has no attribute 'values'”
【发布时间】:2020-01-11 13:55:27
【问题描述】:

我有一个字典数据(从 JSON 导入),如下所示,并希望将其更改为如下所示的 Pandas Dataframe。

date            value        profit
01/06/2020        0        0
01/07/202        0.42        12.59
......            ......        ......
......            ......        ......

第一步原始数据

d_gain

{'error': False, 'message': '', 'dailyGain': [[{'date': '01/06/2020', 'value': 0, 'profit': 0}], [{'date': '01/07/2020', 'value': 0.42, 'profit': 12.59}], [{'date': '01/08/2020', 'value': -14.49, 'profit': -447.42}], [{'date': '01/09/2020', 'value': -12.47, 'profit': 362.38}], [{'date': '01/10/2020', 'value': -12.6, 'profit': -4.28}]]}

第二步

在; d_gain2 = d_gain['dailyGain']

退出;

<class 'list'>

[[{'date': '01/06/2020', 'value': 0, 'profit': 0}], [{'date': '01/07/2020', 'value': 0.42, 'profit': 12.59}], [{'date': '01/08/2020', 'value': -14.49, 'profit': -447.42}], [{'date': '01/09/2020', 'value': -12.47, 'profit': 362.38}], [{'date': '01/10/2020', 'value': -12.6, 'profit': -4.28}]]

然后我尝试转换为DataFrame,但出现错误,

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

请帮我解决这个问题。

谢谢

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    这是因为列表包含每个字典。

    可以

    • 具有匹配键的多个字典包含在列表中。
    • 以列表形式将键作为列和值的字典。

    你能尝试不同的方法吗?

    >>> import pandas as pd
    >>> d_gain2 = [[{'date': '01/06/2020', 'value': 0, 'profit': 0}], [{'date': '01/07/2020', 'value': 0.42, 'profit': 12.59}], [{'date': '01/08/2020', 'value': -14.49, 'profit': -447.42}], [{'date': '01/09/2020', 'value': -12.47, 'profit': 362.38}], [{'date': '01/10/2020', 'value': -12.6, 'profit': -4.28}]]
    >>> df_skel = list()
    >>> for item in d_gain2:
    ...     df_skel.append(item[0])
    ... 
    >>> dataset = pd.DataFrame(df_skel)
    >>> dataset
             date  profit  value
    0  01/06/2020    0.00   0.00
    1  01/07/2020   12.59   0.42
    2  01/08/2020 -447.42 -14.49
    3  01/09/2020  362.38 -12.47
    4  01/10/2020   -4.28 -12.60
    

    祝你有美好的一天!

    【讨论】:

    • 亲爱的,非常感谢!有效。我学到了很多。也有美好的一天!
    猜你喜欢
    • 2023-02-18
    • 2020-04-02
    • 1970-01-01
    • 2020-09-15
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-06-17
    相关资源
    最近更新 更多