在JSON中存储Pandas DataFrame时保持列和行的顺序 [英] Keep column and row order when storing pandas dataframe in json
本文介绍了在JSON中存储Pandas DataFrame时保持列和行的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用to_json将数据存储在json对象中,并使用read_json读取数据时,将返回按字母顺序排序的行和列.有没有办法使结果保持有序或在检索时重新排序?
When storing data in a json object with to_json, and reading it back with read_json, rows and columns are returned sorted alphabetically. Is there a way to keep the results ordered or reorder them upon retrieval?
推荐答案
您可以使用orient='split'
,它将索引和列信息存储在列表中,并保留顺序:
You could use orient='split'
, which stores the index and column information in lists, which preserve order:
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'
,否则您会得到
Just remember to use orient='split'
on reading as well, or you'll get
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
这篇关于在JSON中存储Pandas DataFrame时保持列和行的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文