将 Pandas DataFrame 转换为 JSON 字符串并保存

作者:狼烟四起2024.01.22 15:03浏览量:23

简介:在 Python 中,使用 Pandas 库可以轻松地将 DataFrame 转换为 JSON 格式。以下是实现这一过程的步骤和代码示例。

要将 Pandas DataFrame 转换为 JSON 字符串并保存,你可以按照以下步骤进行操作:

  1. 导入所需的库:
    1. import pandas as pd
    2. import json
  2. 创建 Pandas DataFrame:
    1. data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
    2. df = pd.DataFrame(data)
  3. 将 DataFrame 转换为 JSON 字符串:
    1. json_str = df.to_json(orient='records')
  4. 将 JSON 字符串保存为文件:
    1. with open('output.json', 'w') as f:
    2. f.write(json_str)
    完整代码如下:
    1. import pandas as pd
    2. import json
    3. # 创建 Pandas DataFrame
    4. data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
    5. df = pd.DataFrame(data)
    6. # 将 DataFrame 转换为 JSON 字符串
    7. json_str = df.to_json(orient='records')
    8. # 将 JSON 字符串保存为文件
    9. with open('output.json', 'w') as f:
    10. f.write(json_str)
    运行以上代码后,会在当前目录下生成一个名为 output.json 的文件,其中包含转换后的 JSON 数据。你可以使用任何文本编辑器或 JSON 解析工具打开该文件,查看其中的内容。请注意,to_json() 方法中的 orient 参数设置为 'records',表示将 DataFrame 中的每一行作为一个单独的 JSON 对象进行序列化。如果你希望将整个 DataFrame 作为单个 JSON 对象进行序列化,可以将 orient 参数设置为 'index''columns'。具体选择取决于你的需求。
    另外,如果你希望将 DataFrame 中的数据写入到现有文件中,可以使用 open() 函数打开文件并指定打开模式为 'a'(追加模式),然后写入 JSON 字符串。例如:
    1. with open('existing_file.json', 'a') as f:
    2. f.write(json_str)
    这样会将新的 JSON 数据追加到现有文件的末尾。