在json中存储pandas数据帧时,保持列和行顺序

时间:2017-04-23 14:24:52

标签: python pandas dataframe

当使用to_json将数据存储在json对象中,并使用read_json读回它时,将按字母顺序返回行和列。有没有办法在检索时保持结果排序或重新排序?

3 个答案:

答案 0 :(得分:13)

您可以使用orient='split',它将索引和列信息存储在列表中,从而保留顺序:

In [34]: df
Out[34]: 
   A  C  B
5  0  1  2
4  3  4  5
3  6  7  8

In [35]: df.to_json(orient='split')
Out[35]: '{"columns":["A","C","B"],"index":[5,4,3],"data":[[0,1,2],[3,4,5],[6,7,8]]}'

In [36]: pd.read_json(df.to_json(orient='split'), orient='split')
Out[36]: 
   A  C  B
5  0  1  2
4  3  4  5
3  6  7  8

请记住在阅读时使用orient='split',否则你会得到

In [37]: pd.read_json(df.to_json(orient='split'))
Out[37]: 
  columns       data  index
0       A  [0, 1, 2]      5
1       C  [3, 4, 5]      4
2       B  [6, 7, 8]      3

答案 1 :(得分:0)

如果要使用“ orient ='records'”制作格式并保持列的顺序,请尝试制作类似这样的函数。我认为这不是一个明智的方法,也不建议这样做,因为它不能保证其顺序。

def df_to_json(df):
    res_arr = []
    ldf = df.copy()
    ldf=ldf.fillna('')
    lcolumns = [ldf.index.name] + list(ldf.columns)
    for key, value in ldf.iterrows():
        lvalues = [key] + list(value)
        res_arr.append(dict(zip(lcolumns, lvalues)))
    return json.dumps(res_arr)

此外,如需阅读但无排序的列,请参考此[link](Python json.loads changes the order of the object

祝你好运

答案 2 :(得分:0)

让我们说您有一个熊猫数据框,您已经阅读

alter table t add phonenumber_6 as (format(phonenumber, '000000'));
给出以下内容的

enter image description here

现在有两种使用pandas to_json保存到json的方法 result.sample(200).to_json('abc_sample.json',orient ='split') 将给出像这样一列的顺序 enter image description here

但是,要保留csv中的顺序,请使用此

import pandas as pd
df = pd.read_json ('/abc.json')
df.head()

这将给出结果 enter image description here