如何将 pandas dataframe 转换为 json
通常,您可能有兴趣将 pandas DataFrame 转换为 JSON 格式。
幸运的是,使用to_json()函数可以轻松做到这一点,该函数允许您将 DataFrame 转换为具有以下格式之一的 JSON 字符串:
- ‘split’:像 {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]} 这样的字典
- ‘records’:列表如 [{column -> value}, …, {column -> value}]
- ‘index’:类似 {index -> {column -> value}} 的字典
- ‘columns’:类似 {column -> {index -> value}} 的字典
- ‘values’:只是值数组
- ‘table’:像 {‘schema’: {schema}, ‘data’: {data}} 这样的字典
本教程展示如何使用以下 pandas DataFrame 将 DataFrame 转换为六种格式中的每一种:
import pandas as pd #createDataFrame df = pd.DataFrame({'points': [25, 12, 15, 19], 'assists': [5, 7, 7, 12]}) #view DataFrame df assist points 0 25 5 1 12 7 2 15 7 3 19 12
方法一:“分”
df. to_json (orient=' split ') { "columns": [ "points", "assists" ], "index": [ 0, 1, 2, 3 ], "data": [ [ 25, 5 ], [ 12, 7 ], [ 15, 7 ], [ 19, 12 ] ] }
方法二:“录音”
df. to_json (orient=' records ') [ { "points": 25, “assists”: 5 }, { "points": 12, “assists”: 7 }, { "points": 15, “assists”: 7 }, { "points": 19, “assists”: 12 } ]
方法三:“索引”
df. to_json (orient=' index ') { "0": { "points": 25, “assists”: 5 }, "1": { "points": 12, “assists”: 7 }, "2": { "points": 15, “assists”: 7 }, "3": { "points": 19, “assists”: 12 } }
方法四:“列”
df. to_json (orient=' columns ') { "dots": { "0": 25, "1": 12, "2": 15, "3": 19 }, "assists": { "0": 5, "1": 7, "2": 7, "3": 12 } }
方法五:“价值观”
df. to_json (orient=' values ') [ [ 25, 5 ], [ 12, 7 ], [ 15, 7 ], [ 19, 12 ] ]
方法六:“表格”
df. to_json (orient=' table ') { "plan": { "fields": [ { "name": "index", "type": "integer" }, { "name": "points", "type": "integer" }, { "name": "assists", "type": "integer" } ], "primaryKey": [ "index" ], "pandas_version": "0.20.0" }, "data": [ { "index": 0, "points": 25, “assists”: 5 }, { "index": 1, "points": 12, “assists”: 7 }, { "index": 2, "points": 15, “assists”: 7 }, { "index": 3, "points": 19, “assists”: 12 } ] }
如何导出 JSON 文件
您可以使用以下语法将 JSON 文件导出到计算机上的特定文件路径:
#create JSON file json_file = df. to_json (orient=' records ') #export JSON file with open('my_data.json', 'w') as f: f.write(json_file)
您可以在此处找到 pandas to_json() 函数的完整文档。