编写 Python 代码从文件中读取 JSON 数据并将其转换为数据框、CSV 文件

pythonpandasserver side programmingprogramming更新于 2024/6/21 4:28:17

假设您将以下示例 json 数据存储在文件中,文件名为 pandas_sample.json

{
   "employee": {
      "name": "emp1",
      "salary": 50000,
      "age": 31
   }
}

转换为 csv 后的结果为,

,employee
age,31
name,emp1
salary,50000

解决方案

为了解决这个问题,我们将按照下面给出的步骤 −

  • 创建 pandas_sample.json 文件并存储 JSON 数据。

  • 从文件中读取 json 数据并将其存储为数据。

data = pd.read_json('pandas_sample.json')
  • 将数据转换为数据框

df = pd.DataFrame(data)
  • Apple df.to_csv 函数将数据转换为 csv 文件格式,

df.to_csv('pandas_json.csv')

示例

让我们看看下面的实现以获得更好的理解 −

import pandas as pd
data = pd.read_json('pandas_sample.json')
df = pd.DataFrame(data)
df.to_csv('pandas_json.csv')

输出

employee
age 31
name emp1
salary 50000

相关文章


有用资源