在 pandas 中加载 json 文件-ag捕鱼王app官网

在 pandas 中加载 json 文件

作者:迹忆客 最近更新:2024/04/21 浏览次数:

本教程介绍了如何使用 pandas.read_json() 方法将一个 json 文件加载到 pandas dataframe 中。


将 json 文件加载到 pandas dataframe 中

我们可以使用 pandas.read_json() 函数将 json 文件的路径作为参数传递给 pandas.read_json() 函数,将 json 文件加载到 pandas dataframe 中。

{
    "name": {"1": "anil", "2": "biraj", "3": "apil", "4": "kapil"},
    "age": {"1": 23, "2": 25, "3": 28, "4": 30},
}

示例 data.json 文件的内容如上所示。我们将从上述 json 文件中创建一个 dataframe。

import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated using json file:")
print(df)

输出:

dataframe generated using json file:
    name  age
1   anil   23
2  biraj   25
3   apil   28
4  kapil   30

它显示的是由 data.json 文件中的数据生成的 dataframe。我们必须确保在当前工作目录下有 data.json 文件才能生成 dataframe,否则我们需要提供 json 文件的完整路径作为 pandas.read_json() 方法的参数。

由 json 文件形成的 dataframe 取决于 json 文件的方向。我们一般有三种不同的 json 文件的面向。

  • 面向索引
  • 面向值
  • 面向列

将面向索引的 json 文件加载到 pandas dataframe 中

{
    "0": {"name": "anil", "age": 23},
    "1": {"name": "biraj", "age": 25},
    "2": {"name": "apil", "age": 26},
}

这是一个面向索引的 json 文件的例子,其中顶层键代表数据的索引。

import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from index oriented json file:")
print(df)

输出:

dataframe generated from index oriented json file:
         0      1     2
name  anil  biraj  apil
age     23     25    26

它将从 data.json 文件中创建一个 dataframe,顶层键在 dataframe 中表示为列。

将面向值的 json 文件加载到 pandas dataframe 中

[["anil", 23], ["biraj", 25], ["apil", 26]]

这是一个面向值的 json 文件的例子,数组中的每个元素代表每一行的值。

import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from value oriented json file:")
print(df)

输出:

dataframe generated from value oriented json file:
       0   1
0   anil  23
1  biraj  25
2   apil  26

它将从 data.json 文件中创建一个 dataframe,json 文件中数组的每个元素将在 dataframe 中表示为一行。


将面向列的 json 文件加载到 pandas dataframe 中

{"name": {"1": "anil", "2": "biraj", "3": "apil"}, "age": {"1": 23, "2": 25, "3": 28}}

它是一个面向列的 json 文件顶层索引的例子,代表数据的列名。

import pandas as pd
df = pd.read_json("data.json")
print("dataframe generated from  column oriented json file:")
print(df)

输出:

dataframe generated from column oriented json file:
    name  age
1   anil   23
2  biraj   25
3   apil   28

它将从 data.json 文件中创建一个 dataframe,json 文件的顶层索引将作为 dataframe 中的列名。

上一篇:将 pandas dataframe 写入 csv

下一篇:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:python

pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。

pandas 追加数据到 csv 中

发布时间:2024/04/24 浏览次数:352 分类:python

本教程演示了如何在追加模式下使用 to_csv()向现有的 csv 文件添加数据。

pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:python

本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。

pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:python

本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图