如何从json转换分层DataFrame?

时间:2014-10-21 18:06:11

标签: json pandas

我正在尝试将带有分层行索引的pandas DataFrame存储到json中,然后将其恢复。

import pandas as pd
df = pd.DataFrame({ 'A': ['a','a','b','b'],
                    'B': ['c','d']*2,
                    'C':range(4),
                    'D':[2*i for i in range(4)]
                   })

df = df.set_index(['A','B'])
jsoned_df = df.to_json()
recovered_df = pd.read_json(jsoned_df)

我得到ValueError: No ':' found when decoding object value。这使用to_json和read_json中的默认值orient='columns'

orient的所有the possible values中,只有orient='records'orient='values'不会抛出ValueError。但records丢失行索引,values丢失行索引和列索引。

重现这些尝试:

for orientation in ['split','records','index','columns','values']:
    jsoned = df.to_json(orient=orientation)
    try:
        recovered = pd.read_json(jsoned,orient=orientation)
        print recovered
        print orientation + ' WORKED!!'
    except ValueError:
        print orientation + ' didnt work...'
    print

0 个答案:

没有答案
相关问题