赞
踩
1、to_json
import pandas as pd
from pandas import DataFrame as df
data = df([['a', 'b'], ['c', 'd']], index=['row 1', 'row 2'], columns=['col 1', 'col 2'])
json_columns = data.to_json(orient = "columns") # 返回结果: '{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
json_split = data.to_json(orient = "split") # 返回结果: '{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["a","b"],["c","d"]]}'
json_records = data.to_json(orient = "records") # 返回结果: '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
json_index = data.to_json(orient = "index") # 返回结果:'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
json_values = data.to_json(orient = "values") # 返回结果: '[["a","b"],["c","d"]]'
2、to_dict
json_dict = data.to_dict(orient = "dict") # 返回结果: {'col 1': {'row 1': 'a', 'row 2': 'c'}, 'col 2': {'row 1': 'b', 'row 2': 'd'}}
json_list = data.to_dict(orient = "list") # 返回结果: {'col 1': ['a', 'c'], 'col 2': ['b', 'd']}
json_series = data.to_dict(orient = "series") # 返回结果: {'col 1': row 1 a row 2 c Name: col 1, dtype: object, 'col 2': row 1 b row 2 d Name: col 2, dtype: object}
json_split = data.to_dict(orient = "split") # 返回结果: {'index': ['row 1', 'row 2'], 'columns': ['col 1', 'col 2'], 'data': [['a', 'b'], ['c', 'd']]}
json_records = data.to_dict(orient = "records") # 返回结果: [{'col 1': 'a', 'col 2': 'b'}, {'col 1': 'c', 'col 2': 'd'}]
json_index = data.to_dict(orient = "index") # 返回结果:{'row 1': {'col 1': 'a', 'col 2': 'b'}, 'row 2': {'col 1': 'c', 'col 2': 'd'}}
# 将上述得出的字典进行编码 json.dumps() 转化成 json 形式即可,示例如下:
json.dumps(json_dict)
注:
1、to_json 参数:
2、to_dict 参数:
想知道更多,请关注我的公众号~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。