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-03

In [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)