pandas读json不处理多索引

2024-09-30 22:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读入通过df.to_json()通过pd.read_json创建的数据帧,但是我得到了一个ValueError。我认为这可能与指数是一个多重指数有关,但我不知道该如何处理。在

55k行的原始数据帧称为psi,我通过以下方式创建了test.json

psi.head().to_json('test.json')

Here是{}的输出,如果您想使用它。在

当我对这个小数据集(5行)执行此操作时,我得到一个ValueError。在

^{pr2}$

以下是完整的堆栈:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-1de2f0e65268> in <module>()
      1 get_ipython().system(u' wget https://gist.githubusercontent.com/olgabot/9897953/raw/c270d8cf1b736676783cc1372b4f8106810a14c5/test.json'>)
      2 import pandas as pd
----> 3 pd.read_json('test.json')

/home/obot/virtualenvs/envy/lib/python2.7/site-packages/pandas/io/json.pyc in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit)
    196         obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
    197                           keep_default_dates, numpy, precise_float,
--> 198                           date_unit).parse()
    199 
    200     if typ == 'series' or obj is None:

/home/obot/virtualenvs/envy/lib/python2.7/site-packages/pandas/io/json.pyc in parse(self)
    264 
    265         else:
--> 266             self._parse_no_numpy()
    267 
    268         if self.obj is None:

/home/obot/virtualenvs/envy/lib/python2.7/site-packages/pandas/io/json.pyc in _parse_no_numpy(self)
    481         if orient == "columns":
    482             self.obj = DataFrame(
--> 483                 loads(json, precise_float=self.precise_float), dtype=None)
    484         elif orient == "split":
    485             decoded = dict((str(k), v)

ValueError: No ':' found when decoding object value

> /home/obot/virtualenvs/envy/lib/python2.7/site-packages/pandas/io/json.py(483)_parse_no_numpy()
    482             self.obj = DataFrame(
--> 483                 loads(json, precise_float=self.precise_float), dtype=None)
    484         elif orient == "split":

但是当我对整个数据帧(55k行)执行此操作时,我得到一个invalid pointer error,IPython内核就死了。有什么想法吗?在

EDIT:添加了json最初是如何生成的。在


Tags: intestselfnumpyjsonobjpandashome
3条回答

也可以用orient='table'编写json

df.to_json(path_or_buf='test.json', orient='table')

读取多个索引json

pd.read_json('test.json', orient='table')

这不是ATM实现,请参阅此处的问题:https://github.com/pydata/pandas/issues/4889。在

你可以简单地先重置索引,例如

df.reset_index().to_json(...)

它会起作用的。在

如果要返回多索引结构:

 # save MultiIndex indexes names 
 indexes_names = df.index.names

 df.reset_index().to_json('dump.json')

 # return back MultiIndex structure:
 loaded_df = pd.read_json('dump.json').set_index(indexes_names)

相关问题 更多 >