无法在pandas dateframe

时间:2017-01-23 20:17:22

标签: python json pandas numpy dataframe

我是pandas和python的新手,我在解决这个问题时遇到了麻烦。我有一个复杂的nexted json文件,我想加载到pandas数据帧中。

我使用以下代码:

import json
import urllib.request
import pandas as pd
import numpy as np
from pandas.io.json import json_normalize

file_str = 'C:\\file.json'

with open(file_str, 'r', encoding="utf-8") as json_file:
   json_work = pd.read_json(json_file, typ='series', orient='columns')

for k, v in json_work.items():
    if v is None:
        json_work[k] = "N/A"

##df = pd.DataFrame.from_dict(json_work)

df = pd.io.json.json_normalize(json_work)

print(df)

正如它写的那样我得到了这个错误:

Traceback (most recent call last):
  File "C:/.....hack.py", line 18, in <module>
    df = pd.io.json.json_normalize(json_work)
  File "C:\Users\scoe\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\io\json.py", line 708, in json_normalize
    if any([isinstance(x, dict) for x in compat.itervalues(data[0])]):
  File "C:\Users\scoe\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\compat\__init__.py", line 175, in itervalues
    return iter(obj.values(**kw))
AttributeError: 'str' object has no attribute 'values'

if I swap these two lines to read

df = pd.DataFrame.from_dict(json_work)

##df = pd.io.json.json_normalize(json_work)

该过程成功运行,但结果看起来不像数据帧。输出显示如下:

---- more lines above this, its a sample of the middle of the output ----
hrCenterName                                          KW App Development & Maint
hrSignatureLevel                                                              1H
hrSignatureLevelTitle                             Level 1 HR Signature Authority
imName                                                                         @
imProvider                                                                   N/A
...                                                                          ...
primaryOfficePhoneExtension                                                  N/A
---- more lines after this ----

我做错了什么?

2 个答案:

答案 0 :(得分:2)

json_normalize()期待dict or list of dicts ...

试试这个:

with open(file_str, 'r', encoding="utf-8") as json_file:
   json_work = json.load(json_file)

...

df = pd.io.json.json_normalize(json_work)

答案 1 :(得分:0)

我通常使用pandas来读取JSON,它运行得很好,试一试:

pd.read_json(path)