pandas读写json的知识点

编程入门 行业动态 更新时间:2024-10-25 18:31:00

pandas读写json的<a href=https://www.elefans.com/category/jswz/34/1770093.html style=知识点"/>

pandas读写json的知识点

pandas对象可以直接转换为json,使用to_json即可。里面的orient参数很重要,可选值为columns,index,records,values,split,table

A B C
x 1 4 7
y 2 5 8
z 3 6 9

In [236]: dfjo.to_json(orient="columns")
Out[236]: '{"A":{"x":1,"y":2,"z":3},"B":{"x":4,"y":5,"z":6},"C":{"x":7,"y":8,"z":9}}'# Not available for Series
In [237]: dfjo.to_json(orient="index")
Out[237]: '{"x":{"A":1,"B":4,"C":7},"y":{"A":2,"B":5,"C":8},"z":{"A":3,"B":6,"C":9}}'In [238]: sjo.to_json(orient="index")
Out[238]: '{"x":15,"y":16,"z":17}'
In [239]: dfjo.to_json(orient="records")
Out[239]: '[{"A":1,"B":4,"C":7},{"A":2,"B":5,"C":8},{"A":3,"B":6,"C":9}]'In [240]: sjo.to_json(orient="records")
Out[240]: '[15,16,17]'
In [241]: dfjo.to_json(orient="values")
Out[241]: '[[1,4,7],[2,5,8],[3,6,9]]'# Not available for Series
In [242]: dfjo.to_json(orient="split")
Out[242]: '{"columns":["A","B","C"],"index":["x","y","z"],"data":[[1,4,7],[2,5,8],[3,6,9]]}'In [243]: sjo.to_json(orient="split")
Out[243]: '{"name":"D","index":["x","y","z"],"data":[15,16,17]}'
In [303]: df = pd.DataFrame(.....:     {.....:         "A": [1, 2, 3],.....:         "B": ["a", "b", "c"],.....:         "C": pd.date_range("2016-01-01", freq="d", periods=3),.....:     },.....:     index=pd.Index(range(3), name="idx"),.....: ).....: In [304]: df
Out[304]: A  B          C
idx                 
0    1  a 2016-01-01
1    2  b 2016-01-02
2    3  c 2016-01-03In [305]: df.to_json(orient="table", date_format="iso")
Out[305]: '{"schema":{"fields":[{"name":"idx","type":"integer"},{"name":"A","type":"integer"},{"name":"B","type":"string"},{"name":"C","type":"datetime"}],"primaryKey":["idx"],"pandas_version":"1.4.0"},"data":[{"idx":0,"A":1,"B":"a","C":"2016-01-01T00:00:00.000"},{"idx":1,"A":2,"B":"b","C":"2016-01-02T00:00:00.000"},{"idx":2,"A":3,"B":"c","C":"2016-01-03T00:00:00.000"}]}'

更多推荐

pandas读写json的知识点

本文发布于:2023-11-15 01:27:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591256.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:知识点   pandas   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!