当前位置:   article > 正文

python DataFrame 转化为 json_python dataframe怎么快速转为json

python dataframe怎么快速转为json

python DataFrame 转化为 json

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"]]'

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
'
运行

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

注:
1、to_json 参数:

  • orient 值不同 json 的格式也不同
  • Series:默认’index’,允许的值:‘split’、‘records’、‘index’、‘table’
  • DataFrame:默认’columns’,允许的值:‘split’、‘records’、‘index’、‘columns’、‘values’、‘table’

2、to_dict 参数:

  • DataFrame:默认:‘dict’,允许的值:‘dict’、‘list’、‘series’、‘split’、‘records’、‘index’

想知道更多,请关注我的公众号~
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/856826
推荐阅读
相关标签
  

闽ICP备14008679号