dataframe.to_json()

时间:2017-05-04 07:39:34

标签: python json pandas

我的数据框l是这样的:

                            0    1
Sepal Length  Label     
(4.296, 5.2]  setosa        39   0.866667
              versicolor     5   0.111111
              virginica      1   0.022222
(5.2, 6.1]    setosa        11   0.220000
              versicolor    29   0.580000
              virginica     10   0.200000
(6.1, 7]      versicolor    16   0.372093
              virginica     27   0.627907
(7, 7.9]      virginica     12   1.000000

然后执行ll = l.to_json(),结果为:

'{"0":{"["(4.296, 5.2]","setosa"]":39,"["(4.296, 5.2]","versicolor"]":5,"["(4.296, 5.2]","virginica"]":1,"["(5.2, 6.1]","setosa"]":11,"["(5.2, 6.1]","versicolor"]":29,"["(5.2, 6.1]","virginica"]":10,"["(6.1, 7]","versicolor"]":16,"["(6.1, 7]","virginica"]":27,"["(7, 7.9]","virginica"]":12},"1":{"["(4.296, 5.2]","setosa"]":0.8666666667,"["(4.296, 5.2]","versicolor"]":0.1111111111,"["(4.296, 5.2]","virginica"]":0.0222222222,"["(5.2, 6.1]","setosa"]":0.22,"["(5.2, 6.1]","versicolor"]":0.58,"["(5.2, 6.1]","virginica"]":0.2,"["(6.1, 7]","versicolor"]":0.3720930233,"["(6.1, 7]","virginica"]":0.6279069767,"["(7, 7.9]","virginica"]":1.0}}'

然后我尝试读取ll,执行pd.read_json(ll)并失败。以下是消息:

ValueError                                Traceback (most recent call last)
<ipython-input-574-4cb1a3ab2e3c> in <module>()
----> 1 pd.read_json(l1g)

/home/lv/anaconda3/lib/python3.6/site-packages/pandas/io/json.py in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit, encoding, lines)
    279         obj = FrameParser(json, orient, dtype, convert_axes, convert_dates,
    280                           keep_default_dates, numpy, precise_float,
--> 281                           date_unit).parse()
    282 
    283     if typ == 'series' or obj is None:

/home/lv/anaconda3/lib/python3.6/site-packages/pandas/io/json.py in parse(self)
    347 
    348         else:
--> 349             self._parse_no_numpy()
    350 
    351         if self.obj is None:

/home/lv/anaconda3/lib/python3.6/site-packages/pandas/io/json.py in _parse_no_numpy(self)
    564         if orient == "columns":
    565             self.obj = DataFrame(
--> 566                 loads(json, precise_float=self.precise_float), dtype=None)
    567         elif orient == "split":
    568             decoded = dict((str(k), v)

ValueError: No ':' found when decoding object value

我想保存数据的multiIndex结构,所以怎么做

任何人都可以帮助我吗?谢谢&gt;。&lt;

1 个答案:

答案 0 :(得分:0)

pandas json导出和往返仍然难以使用MultiIndex(根据this github issue

解决此问题的一种方法是在导出之前执行public static void checkSelected() { boolean check = true; for (boolean radioChecked : checked) { if(Boolean.TRUE != radioChecked){ check = false; break; } } if (check) buttonCheckAnswer.setVisibility(View.VISIBLE); ,之后执行reset_index,如github问题和this previous answer

中所述

您是否尝试过其中一个set_index&#39;(pandas documentation