gpt4 book ai didi

python - 当我尝试将 JSON 转换为 Pandas Dataframe 时,出现错误 "AttributeError: ' list' object has no attribute 'values'

转载 作者:行者123 更新时间:2023-12-01 06:35:20 26 4
gpt4 key购买 nike

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

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

第1步原始数据

d_增益

{'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}]]}

第 2 步

在; d_gain2 = d_gain['每日增益']

输出;

<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'

请帮我解决这个问题。

谢谢

最佳答案

发生这种情况是因为列表包含每个字典。

可以是

  • 多个字典,其匹配键包含在列表中。
  • 字典,键为列,值为列表形式。

你能尝试不同的方法吗?

>>> 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

祝你有美好的一天!

关于python - 当我尝试将 JSON 转换为 Pandas Dataframe 时,出现错误 "AttributeError: ' list' object has no attribute 'values',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com