【问题标题】:ValueError: DataFrame constructor not properly called when convert Json data to DataframeValueError:将 Json 数据转换为 DataFrame 时未正确调用 DataFrame 构造函数
【发布时间】:2019-02-18 03:47:59
【问题描述】:

当我尝试使用 pandas 和 json 包将 Json 数据转换为 Dataframe 时遇到问题。

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

{"Number":41,"Type":["A1","A2","A3","A4","A5"],"Percent":{"Very Good":1.2,"Good":2.1,"OK":1.1,"Bad":1.3,"Very Bad":1.7}}

我的代码是:

import pandas as pd
import json

with open('Test.json', 'r') as filename:
    json_file=json.load(filename)
    df =pd.DataFrame(json_file['Type'],columns=['Type'])

问题是当我只从 Json 文件中读取类型时,它给了我正确的结果,如下所示:

   Type
0   A1
1   A2
2   A3
3   A4
4   A5

但是当只从 Json 文件中读取 Number 时:

 df =pd.DataFrame(json_file['Number'],columns=['Number'])

它给了我错误:ValueError: DataFrame 构造函数没有正确调用!

如果我使用:

df = pd.DataFrame.from_dict(json_file)

我得到错误:

ValueError:将 dicts 与非系列混合可能会导致排序不明确。

我对谷歌做了一些研究,但仍然不知道为什么。

我的目标是将这个 Json 数据分成两个 Dataframe,第一个是将 Number 和 Type 组合在一起:

   Number  Type
0    41     A1
1    41     A2
2    41     A3
3    41     A4
4    41     A5

我要获取的另一个 Dataframe 是 Percent 中的数据,可能如下所示:

Very Good  1.2
Good 2.1
OK 1.1
Bad 1.3
Very Bad 1.7

【问题讨论】:

  • 看看pandas read_json

标签: python-3.x pandas


【解决方案1】:

这应该会给出你想要的输出:

with open('Test.json', 'r') as filename:
    json_file=json.load(filename)
    df = pd.DataFrame({'Number': json_file.get('Number'), 'Type': json_file.get('Type')})
    df2 = pd.DataFrame({'Percent': json_file.get('Percent')})

   Number type
0      41   A1
1      41   A2
2      41   A3
3      41   A4
4      41   A5

           Percent
Bad            1.3
Good           2.1
OK             1.1
Very Bad       1.7
Very Good      1.2

您可以将其概括为一个函数:

def json_to_df(d, ks):
    return pd.DataFrame({k: d.get(k) for k in ks})

df = json_to_df(json_file, ['Number', 'Type'])

如果你想避免使用 json 包,你可以直接在 pandas 中进行:

_df = pd.read_json('Test.json', typ='series')
df = pd.DataFrame.from_dict(dict(_df[['Number', 'Type']]))
df2 = pd.DataFrame.from_dict(_df['Percent'], orient='index', columns=['Percent'])

【讨论】:

  • 您好,非常感谢您的回复,我对我的问题进行了一些调整,我查看了实际数据,它比我之前发布的更复杂,您能给我一些想法吗?
猜你喜欢
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2019-02-11
  • 1970-01-01
  • 2020-01-22
  • 2017-07-27
  • 2014-10-25
  • 2019-11-08
相关资源
最近更新 更多